﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Dynamic;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using Trade.Mail;
using Trade.DBUtility;
using Trade.DBUtility.DataTableName;

using MailService;
using MailService.Mime;
using MailService.Pop3Mail;
using MailService.Security;
using MailService.SmtpMail;

using Custom.UI;
using Custom.UI.MailBox;
using HOTERP.BLL;

namespace TradeWeb.Controllers
{
    public class MailBoxController : Controller
    {
        #region 接收功能相关方法：递归查询，获取到邮箱系统目录的列表；
        List<int> _iSubFolderIDList = new List<int>();
        private void GetFolderIDWhere(bool bISNeedReadDB, DataTable dtMailFolder, string strUserCode, string strAccountName, int iParentID)
        {
            SqlConnection sqlConnTemp = new SqlConnection(strConnectString);
            if (bISNeedReadDB)
            {
                //查询用户的AutoMoveFolder信息
                string strSQLFolder = "SELECT * FROM T_MailFolder Where UserCode='" + strUserCode + "'";
                string strTableFolder = "T_MailFolder";
                DataSet ds = null;
                //
                DataTableName dtnFolder = new DataTableName();
                dtnFolder.strSelectSQL = strSQLFolder;
                dtnFolder.strTableName = strTableFolder;
                try
                {
                    ds = CustomizableDesignBLL.GetData(dtnFolder, false);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                dtMailFolder.Rows.Clear();
                dtMailFolder.Merge(ds.Tables[0]);
            }
            DataRow[] drSelectRows;
            int iFolderID;
            drSelectRows = dtMailFolder.Select("UserCode='" + strUserCode + "' AND AccountName='" + strAccountName + "' AND ParentFolderID = " + iParentID.ToString(), "FolderName ASC");
            foreach (DataRow drRow in drSelectRows)
            {
                iFolderID = (int)drRow["FolderID"];
                _iSubFolderIDList.Add(iFolderID);
                //遍历递归，即取出iFolerID的列表；
                this.GetFolderIDWhere(false, dtMailFolder, strUserCode, strAccountName, iFolderID);
            }
        }
        #endregion

        string strConnectString = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;

        #region 服务器，邮箱系统收取功能；
        public string ServerReceiveMails(string strUserCode,string strAccountName) 
        {
            string jsonResult = string.Empty;
            DataSet dsNewMailBox = null;
            //即时变量，一次赋值，一次使用；

            DataSet dsData = null;
            List<DataTableName> lstDTNData = new List<DataTableName>();
            DataTableName dtnData = null;
            #region 获取邮箱帐户信息
            dtnData = new DataTableName();
            dtnData.strSelectSQL = "SELECT AccountName,UserCode,UserName,MailPassword,BackType,UserMail,MailAddress,POP3Server,POP3Port  FROM T_MailAccount WHERE  UserCode=@UserCode and AccountName=@AccountName ";
            dtnData.strTableName = "MailAccount";
            dtnData.SqlSelectParameterList.Add(new SqlParameter("@UserCode", strUserCode));
            dtnData.SqlSelectParameterList.Add(new SqlParameter("@AccountName", strAccountName));
            lstDTNData.Add(dtnData);
            //
            dtnData = new DataTableName();
            dtnData.strSelectSQL = "Select AutoMoveFolder FROM T_User WHERE UserCode='" + strUserCode + "'";
            dtnData.strTableName = "Folder";
            dtnData.SqlSelectParameterList.Clear();
            lstDTNData.Add(dtnData);
            try
            {
                dsData = CustomizableDesignBLL.GetData(lstDTNData, false);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false ,\"data\":{},\"message\":\"系统查询邮箱帐户失败！\"}";
                return jsonResult;
            }
            if (dsData == null || (!dsData.Tables.Contains("MailAccount")) || dsData.Tables["MailAccount"].DefaultView.Count <= 0)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"邮箱帐户不存在！\"}";
                return jsonResult;
            }
            #endregion

            DataSet dsMailBox = null;
            List<DataTableName> lstDTNMailBox = new List<DataTableName>();
            DataTableName dtnMailBox = null;
            #region 查询邮箱系统的表结构信息
            //
            dtnMailBox = new DataTableName();
            dtnMailBox.strSelectSQL = "SELECT * FROM T_ReceivedMailUIDL WHERE 1=2";
            dtnMailBox.strTableName = "T_ReceivedMailUIDL";
            lstDTNMailBox.Add(dtnMailBox);
            //
            dtnMailBox = new DataTableName();
            dtnMailBox.strSelectSQL = "SELECT * FROM T_MailBox WHERE 1=2";
            dtnMailBox.strTableName = "T_MailBox";
            lstDTNMailBox.Add(dtnMailBox);
            //
            dtnMailBox = new DataTableName();
            dtnMailBox.strSelectSQL = "SELECT * FROM T_MailBox1 WHERE 1=2";
            dtnMailBox.strTableName = "T_MailBox1";
            lstDTNMailBox.Add(dtnMailBox);
            //
            dtnMailBox = new DataTableName();
            dtnMailBox.strSelectSQL = "SELECT * FROM T_MailBox2 WHERE 1=2";
            dtnMailBox.strTableName = "T_MailBox2";
            lstDTNMailBox.Add(dtnMailBox);
            try
            {
                dsMailBox = CustomizableDesignBLL.GetData(lstDTNMailBox, false);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false ,\"data\":{},\"message\":\"系统查询邮件表结构失败！\"}";
                return jsonResult;
            }
            #endregion

            DataSet dsMailDomainName = null;
            #region 获取不归档的邮件列表
            DataTableName dtnNoDomain = new DataTableName();
            dtnNoDomain.strSelectSQL = "SELECT MailDomainName FROM T_MailDomainName";
            dtnNoDomain.strTableName = "T_MailDomainName";
            try
            {
                dsMailDomainName = CustomizableDesignBLL.GetData(dtnNoDomain, false);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"系统查询不归档邮件失败！\"}";
                return jsonResult;
            }
            #endregion

            DataSet dsMailBlackList = null;
            #region 获取黑名单
            DataTableName dtnBlackList = new DataTableName();
            dtnBlackList.strSelectSQL = "SELECT * FROM T_MailBlackList where UserCode='" + strUserCode + "'";
            dtnBlackList.strTableName = "T_MailBlackList";
            try
            {
                dsMailBlackList = CustomizableDesignBLL.GetData(dtnBlackList, false);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"系统查询黑名单失败！\"}";
                return jsonResult;
            }
            #endregion

            string _strUserCode = dsData.Tables["MailAccount"].DefaultView[0]["UserCode"].ToString();
            string _strAccountName = dsData.Tables["MailAccount"].DefaultView[0]["AccountName"].ToString();
            string _strBackType = dsData.Tables["MailAccount"].DefaultView[0]["BackType"].ToString();
            string _strMailAddress = dsData.Tables["MailAccount"].DefaultView[0]["MailAddress"].ToString();
            string _strMailPassword = dsData.Tables["MailAccount"].DefaultView[0]["MailPassword"].ToString();
            string _strPOP3Server = dsData.Tables["MailAccount"].DefaultView[0]["POP3Server"].ToString();
            int iPOP3Port = dsData.Tables["MailAccount"].DefaultView[0]["POP3Port"] == DBNull.Value ? 110 : Convert.ToInt32(dsData.Tables["MailAccount"].DefaultView[0]["POP3Port"]);
            string _DESKey = "8^@a)2.Y";
            _strMailPassword = Trade.DBUtility.EncryptDecryptService.DESDecrypt(_DESKey, _strMailPassword);

            try
            {
                //连接POP3服务器
                Pop3 pop = new Pop3();
                pop.Connect(_strPOP3Server, iPOP3Port, true);
                AuthenticationMethods MoAuthMethods = AuthenticationMethods.Auto;
                pop.Login(_strMailAddress,_strMailPassword, MoAuthMethods);

                //获取邮件服务器中的收取历史的ID集合
                string[] listMailUids = pop.GetMessageUids();
                List<string> listReceiveMails = new List<string>();
                List<string> listDeleteMails = new List<string>();

                string strSQLReceivedOld = string.Empty;
                DataSet dsReceivedMailUIDL = new DataSet();
                //收件ID集合，拼接出查询in条件；
                string strReceivedMailUIDLWhere = "";
                int iReceivedMailUIDLCount = 0;
                int iReceiveCount = 0;

                #region 获取需要收取的邮件的UID集合，以及需要删除的邮件集合（邮箱帐号已删除，Z版智桥系统也要删除）
                foreach (string emailUid in listMailUids)
                {
                    iReceivedMailUIDLCount++;
                    if (strReceivedMailUIDLWhere == "")
                        strReceivedMailUIDLWhere = "'" + emailUid + "'";
                    else
                        strReceivedMailUIDLWhere = strReceivedMailUIDLWhere + ",'" + emailUid + "'";
                    if (iReceivedMailUIDLCount % 500 == 0 || iReceivedMailUIDLCount == listMailUids.Length)
                    {
                        strSQLReceivedOld = "SELECT MailUIDL,ReceiveTime FROM T_ReceivedMailUIDL WHERE UserCode='" + strUserCode + "' AND AccountName='" + strAccountName + "' AND MailUIDL IN(" + strReceivedMailUIDLWhere + ")";
                        strReceivedMailUIDLWhere = "";
                    }
                }
                DataTableName dtnReceivedMailUIDL = new DataTableName();
                dtnReceivedMailUIDL.strSelectSQL = strSQLReceivedOld;
                dtnReceivedMailUIDL.strTableName = "ReceivedOld";
                try
                {
                    dsReceivedMailUIDL = CustomizableDesignBLL.GetData(dtnReceivedMailUIDL, false);
                }
                catch (Exception)
                {

                }
                DataRow[] drReceivedMailUIDLRows;
                int iDay;
                DateTime dtReceiveTime;
                DateTime dtNow =DateTime.Now;

                foreach (string emailUid in listMailUids)
                {
                    foreach (DataTable dt in dsReceivedMailUIDL.Tables)
                    {
                        drReceivedMailUIDLRows = dt.Select("MailUIDL='" + emailUid + "'");
                        //收取
                        if (drReceivedMailUIDLRows.Length == 0)
                            listReceiveMails.Add(emailUid);
                        //删除邮件
                        if (_strBackType == "立即删除")
                        {
                            listDeleteMails.Add(emailUid);
                        }
                        else
                        {
                            iDay = 0;
                            if (_strBackType == "保留2周")
                                iDay = 14;
                            if (_strBackType == "保留1个月")
                                iDay = 30;
                            if (_strBackType == "保留3个月")
                                iDay = 90;
                            if (_strBackType == "保留6个月")
                                iDay = 180;
                            if (iDay > 0 && drReceivedMailUIDLRows.Length > 0)
                            {
                                dtReceiveTime = (DateTime)drReceivedMailUIDLRows[0]["ReceiveTime"];
                                if (dtReceiveTime.AddDays(iDay) < dtNow)
                                {
                                    listDeleteMails.Add(emailUid);
                                }
                            }
                        }
                    }
                }
                #endregion

                #region Z版系统收取邮件需要处理的参数
                //收取邮件 
                MailService.Mime.MailMessage mail = null;
                int iMailUidIndex;
                DataRow drReceiveMailUIDL;
                DataRow drMailBox;
                DataRow drMailBox1;
                DataRow drMailBox2;
                List<string> strCidList;
                string strSender;
                string strToList;   //用于分解收件人列表
                string strToName;   //用于分解收件人名称
                string strToMail;  //用于分解收件人邮件地址
                int iToIndex;
                string strHtmlBody;
                string strTextBody;
                string strBody;
                bool bISReceivedIP = false; ;
                string strReceivedIP = "";
                bool bISOriginatingIP = false;
                string strOriginatingIP = "";
                int iReceiveStart;
                int iReceiveEnd;
                string strOrgIP;
                string strOrgAddress;
                string strMailGUID;
                string strLocalPath;
                int iMailSize;
                //客户信息
                string strClientCode;
                string strClientType;
                string strClientName;
                string strContactName;
                string strCountry;
                string strWhere = "";
                MailBoxCommon.MailFolder mailFolder;
                int iNewFolderID;
                int iFolderID;
                //
                CountryFromIP CountryFromIPSrv = new CountryFromIP();
                string strGetCountryFromIPErrorMsg;
                #endregion

                foreach (string emailUid in listReceiveMails)
                {
                    //邮件对象；获取到需要收取的新邮件对象
                    iMailUidIndex = pop.GetMessageIndexFromUid(emailUid);
                    mail = pop.DownloadMessageHeader(iMailUidIndex);
                    iMailSize = mail.SizeOnServer;
                    mail = pop.DownloadEntireMessage(iMailUidIndex);

                    #region 保存到本地，使邮件本地化
                    /*
                     * 1、新邮件的GUID;
                     * 2、CS客户端路径：strDBMailPath;
                     * 3、CS服务端路径：strWebMailPath;
                     * 4、
                     */
                    strMailGUID = System.Guid.NewGuid().ToString();
                    //格式化邮箱帐号的名称
                    strAccountName = strAccountName.Replace('\\', '_').Replace('/', '_').Replace('"', '_').Replace('<', '_').Replace('>', '_').Replace('|', '_').Replace('\b', '_').Replace('\0', '_').Replace('\t', '_').Replace('?', '_').Replace('*', '_').Replace(':', '_');
                    //CS服务器目录
                    string strBoxMailDir = "AppMail/MailBox/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + strUserCode + strAccountName + "/In/";
                    //CS服务器路径
                    string strBoxMailPath = strBoxMailDir + strMailGUID + ".eml";


                    //Web根路径
                    string strWebRoot = Server.MapPath("/ftp");
                    if (!System.IO.Directory.Exists(strWebRoot))
                        System.IO.Directory.CreateDirectory(strWebRoot);
                    if (!strWebRoot.EndsWith("\\"))
                        strWebRoot = strWebRoot + "\\";
                    //WebTrunk路径
                    string strWebTrunkDir = "AppMail\\MailBox\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + strUserCode +strAccountName + "\\In\\";
                    string strServerDir = strWebRoot + strWebTrunkDir;
                    if (!System.IO.Directory.Exists(strServerDir))
                        System.IO.Directory.CreateDirectory(strServerDir);
                    //IIS路径保存本地邮件
                    strLocalPath = strServerDir + "\\" + strMailGUID + ".eml";



                    //感觉休眠一个比较好一点,这个大附件是个问题,NET内存不太好回收
                    //System.Threading.Thread.Sleep(500);
                    if (iMailSize > 3 * 1024 * 1024)
                        GC.Collect();
                    if (!mail.SaveMessage(strLocalPath))
                    {
                        jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"邮件无法保存到目录中！\"}";
                        return jsonResult;
                    }
                    if (!System.IO.File.Exists(strLocalPath))
                    {
                        jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"邮件无法保存到目录中！\"}";
                        return jsonResult;
                    }
                    //感觉休眠一个比较好一点,这个大附件是个问题,NET内存不太好回收
                    //System.Threading.Thread.Sleep(500);
                    if (iMailSize > 3 * 1024 * 1024)
                        GC.Collect();
                    #endregion

                    //邮件收取表
                    drReceiveMailUIDL = dsMailBox.Tables["T_ReceivedMailUIDL"].NewRow();
                    drReceiveMailUIDL["AccountName"] = strAccountName;
                    drReceiveMailUIDL["UserCode"] = strUserCode;
                    drReceiveMailUIDL["MailUIDL"] = emailUid;
                    drReceiveMailUIDL["ReceiveTime"] = dtNow;
                    drReceiveMailUIDL["MailGUID"] = strMailGUID;
                    dsMailBox.Tables["T_ReceivedMailUIDL"].Rows.Add(drReceiveMailUIDL);
                    //收取箱
                    drMailBox = dsMailBox.Tables["T_MailBox"].NewRow();
                    drMailBox["MailGUID"] = strMailGUID;
                    drMailBox["UserCode"] = strUserCode;
                    drMailBox["AccountName"] = strAccountName;
                    drMailBox["Writer"] = strUserCode;
                    drMailBox["MailUIDL"] = emailUid;
                    drMailBox["ISRead"] = false;
                    drMailBox["ISMarking"] = false;
                    drMailBox["ISImportant"] = false;
                    drMailBox["ISRevert"] = false;
                    drMailBox["ISFwd"] = false;
                    drMailBox["ISFwdInSide"] = false;
                    try
                    {
                        drMailBox["ISReceipt"] = mail.ConfirmRead.Trim() != string.Empty || mail.ConfirmReceipt.Trim() != string.Empty;
                    }
                    catch
                    {
                        drMailBox["ISReceipt"] = false;
                    }

                    #region 判断是否垃圾邮箱

                    string strFormEmail = mail.From == null ? string.Empty : mail.From.Email;
                    string strFormEmailDomain = "";
                    if (strFormEmail.Split('@').Length > 1)
                        strFormEmailDomain = strFormEmail.Split('@')[1];
                    string strBoxType = MailBoxCommon.MailBoxType.InBox.ToString();
                    foreach (DataRowView drv in dsMailBlackList.Tables[0].DefaultView)
                    {
                        if (drv["BlackType"].ToString() == "邮件地址")
                        {
                            if (drv["BlackRule"].ToString().ToLower() == strFormEmail.ToLower())
                            {
                                strBoxType = MailBoxCommon.MailBoxType.Spam.ToString();
                                break;
                            }
                        }
                        if (drv["BlackType"].ToString() == "邮件地址域")
                        {
                            if (strFormEmailDomain != "")
                            {
                                if (drv["BlackRule"].ToString().ToLower() == strFormEmailDomain.ToLower())
                                {
                                    strBoxType = MailBoxCommon.MailBoxType.Spam.ToString();
                                    break;
                                }
                            }
                        }
                    }
                    #endregion

                    drMailBox["BoxType"] = strBoxType;
                    drMailBox["Charset"] = mail.Charset;
                    drMailBox["Priority"] = mail.Priority;
                    drMailBox["ISAttachment"] = false;
                    #region 邮件内容处理
                    try
                    {
                        strTextBody = mail.BodyPlainText;
                    }
                    catch
                    {
                        strTextBody = "";
                    }
                    try
                    {
                        strHtmlBody = mail.BodyHtmlText;
                    }
                    catch
                    {
                        strHtmlBody = "";
                    }
                    if (String.IsNullOrEmpty(strHtmlBody))
                    {
                        strBody = System.Web.HttpUtility.HtmlEncode(strTextBody);
                        if (strTextBody != string.Empty)    //强制转换为HTML
                            strBody = "<DIV><FONT face=Arial Narrow size=2>" + strBody.Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>") + "</FONT></DIV>";
                    }
                    else
                    {
                        strBody = strHtmlBody;
                    }
                    strCidList = new MailCommon().GetCidContentID(strBody);
                    foreach (MailService.Mime.Attachment attachment in mail.Attachments)
                    {
                        if (strCidList.IndexOf(attachment.ContentID) < 0)
                        {
                            drMailBox["ISAttachment"] = true;
                            break;
                        }
                    }
                    strSender = mail.From == null ? string.Empty : mail.From.Email;
                    drMailBox["Sender"] = strSender;
                    drMailBox["SenderName"] = mail.From == null ? string.Empty : mail.From.DisplayName;

                    #region 分解收件人信息
                    strToList = string.Empty;
                    iToIndex = 0;
                    foreach (MailService.Mime.EmailAddress maTo in mail.To)
                    {
                        iToIndex++;
                        strToName = maTo.DisplayName;
                        strToMail = maTo.Email;
                        strToName = strToName == null ? string.Empty : strToName;
                        strToList += strToName + "<" + strToMail + ">";
                        if (iToIndex < mail.To.Count)
                            strToList += ";";
                    }
                    #endregion
                    drMailBox["ToList"] = strToList;

                    #region 分解收件人信息
                    strToList = string.Empty;
                    iToIndex = 0;
                    foreach (MailService.Mime.EmailAddress maTo in mail.Cc)
                    {
                        iToIndex++;
                        strToName = maTo.DisplayName;
                        strToMail = maTo.Email;
                        strToName = strToName == null ? string.Empty : strToName;
                        strToList += strToName + "<" + strToMail + ">";
                        if (iToIndex < mail.Cc.Count)
                            strToList += ";";
                    }
                    #endregion
                    drMailBox["CcList"] = strToList;
                    drMailBox["BccList"] = "";
                    try
                    {
                        if (mail.DateReceived == null || string.Compare(mail.DateReceived.ToString("yyyy-MM-dd"), "2000-01-01") < 0)
                        {
                            if (mail.Date == null || string.Compare(mail.Date.ToString("yyyy-MM-dd"), "2000-01-01") < 0)
                                drMailBox["InSentTime"] = dtNow;
                            else
                                drMailBox["InSentTime"] = mail.Date;
                        }
                        else
                        {
                            drMailBox["InSentTime"] = mail.DateReceived;
                        }
                    }
                    catch (Exception)
                    {
                        drMailBox["InSentTime"] = dtNow;
                    }

                    #region 处理一下InSentTime
                    if (drMailBox["InSentTime"] == DBNull.Value)
                    {
                        drMailBox["InSentTime"] = dtNow;
                    }
                    else
                    {
                        if (string.Compare(((DateTime)drMailBox["InSentTime"]).ToString("yyyy-MM-dd"), "2000-01-01") < 0)
                            drMailBox["InSentTime"] = dtNow;
                    }
                    #endregion

                    drMailBox["Subject"] = mail.Subject;
                    if (strBoxType == MailBoxCommon.MailBoxType.Spam.ToString())
                        drMailBox["FolderID"] = MailBoxCommon._iParentFolderIDSpam;
                    else
                        drMailBox["FolderID"] = MailBoxCommon._iParentFolderIDInBox;
                    drMailBox["SessionID"] = -1;

                    #endregion

                    #region 邮件头信息处理：邮件大小，分组，发送地址，IP路径
                    
                    if (mail.Headers != null)
                    {
                        string strSessionID;
                        int iSessionID;
                        try
                        {
                            strSessionID = mail.Headers["SessionID"];
                            if (int.TryParse(strSessionID, out iSessionID))
                                drMailBox["SessionID"] = iSessionID;
                        }
                        catch { }
                    }
                    drMailBox["MailGroup"] = "";
                    drMailBox["MailPath"] = strBoxMailPath;
                    drMailBox["MailSize"] = iMailSize;
                    drMailBox["RevertMailGUID"] = "";
                    drMailBox["FwdMailGUID"] = "";

                    //
                    bISReceivedIP = false; ;
                    strReceivedIP = "";
                    bISOriginatingIP = false;
                    strOriginatingIP = "";
                    strOrgIP = "";
                    foreach (MailService.Mime.Header hearder in mail.Headers)
                    {
                        if (hearder.Name.ToLower() == "Received".ToLower())
                        {
                            iReceiveStart = hearder.Value.IndexOf("[");
                            iReceiveEnd = hearder.Value.IndexOf("]");
                            if (iReceiveStart >= 0 && iReceiveEnd >= 0 && iReceiveEnd > iReceiveStart)
                            {
                                bISReceivedIP = true;
                                if (strReceivedIP == string.Empty)
                                    strReceivedIP = hearder.Value.Substring(iReceiveStart + 1, iReceiveEnd - iReceiveStart - 1);
                                else
                                    strReceivedIP = strReceivedIP + ";" + hearder.Value.Substring(iReceiveStart + 1, iReceiveEnd - iReceiveStart - 1);
                            }
                        }
                        if (hearder.Name.ToLower() == "X-Mda-Received".ToLower())
                        {
                            iReceiveStart = hearder.Value.IndexOf("[<");
                            iReceiveEnd = hearder.Value.IndexOf(">]");
                            if (iReceiveStart >= 0 && iReceiveEnd >= 0 && iReceiveEnd > iReceiveStart)
                            {
                                bISReceivedIP = true;
                                if (strReceivedIP == string.Empty)
                                    strReceivedIP = hearder.Value.Substring(iReceiveStart + 2, iReceiveEnd - iReceiveStart - 2);
                                else
                                    strReceivedIP = strReceivedIP + ";" + hearder.Value.Substring(iReceiveStart + 2, iReceiveEnd - iReceiveStart - 2);
                            }
                        }
                        if (hearder.Name.ToLower() == "X-Originating-IP".ToLower())
                        {
                            bISOriginatingIP = true;
                            if (strOriginatingIP == string.Empty)
                                strOriginatingIP = hearder.Value;
                            else
                                strOriginatingIP = strOriginatingIP + ";" + hearder.Value;
                        }
                    }
                    if (bISOriginatingIP)
                    {
                        strOrgIP = strOriginatingIP;
                    }
                    else
                    {
                        if (bISReceivedIP)
                        {
                            strOrgIP = strReceivedIP;
                        }
                    }
                    drMailBox["OrgIP"] = strOrgIP.Replace("[", "").Replace("]", "");
                    strOrgAddress = "";
                    string[] strOrgIPs = strOrgIP.Split(';');
                    for (int i = 0; i < strOrgIPs.Length; i++)
                    {
                        if (strOrgIPs[i].Trim() == string.Empty)
                            continue;
                        strGetCountryFromIPErrorMsg = "";
                        CountryFromIPSrv = new CountryFromIP();
                        string strOrgAddressTemp = CountryFromIPSrv.GetCountryFromIP(strOrgIPs[i].Replace("[", "").Replace("]", ""), out strGetCountryFromIPErrorMsg);
                        if (strOrgAddressTemp == "-1")
                            continue;
                        if (strOrgAddress == "")
                            strOrgAddress = strOrgAddressTemp;
                        else
                            strOrgAddress = strOrgAddress + ";" + strOrgAddressTemp;
                    }
                    drMailBox["OrgAddress"] = strOrgAddress;
                    #endregion

                    #region 邮件的客户信息处理

                    strClientCode = "";
                    strClientType = "";
                    strClientName = "";
                    strContactName = "";
                    strCountry = "";
                    drMailBox["ClientType"] = strClientType;
                    drMailBox["ClientCode"] = strClientCode;
                    drMailBox["ClientName"] = strClientName;
                    drMailBox["ContactName"] = strContactName;
                    drMailBox["Country"] = strCountry;
                    drMailBox["PurposeModuleName"] = "";
                    drMailBox["PurposePKCode"] = "";
                    drMailBox["PurposeDesc"] = "";
                    drMailBox["ISTrack"] = false;
                    dsMailBox.Tables["T_MailBox"].Rows.Add(drMailBox);
                    //
                    drMailBox1 = dsMailBox.Tables["T_MailBox1"].NewRow();
                    drMailBox1["MailGUID"] = strMailGUID;
                    drMailBox1["AccountName"] = strAccountName;
                    drMailBox1["UserCode"] = strUserCode;
                    drMailBox1["TextBody"] = strTextBody;
                    dsMailBox.Tables["T_MailBox1"].Rows.Add(drMailBox1);
                    //
                    drMailBox2 = dsMailBox.Tables["T_MailBox2"].NewRow();
                    drMailBox2["MailGUID"] = strMailGUID;
                    drMailBox2["AccountName"] = strAccountName;
                    drMailBox2["UserCode"] = strUserCode;
                    drMailBox2["LocalPath"] = strLocalPath;
                    drMailBox2["MailPath"] =strBoxMailPath;
                    drMailBox2["FileMD5"] =Custom.UI.Common.GetMD5HashFromFile(strLocalPath);
                    drMailBox2["TransferSucc"] = true;
                    drMailBox2["TransferErrorDesc"] = "上传完成";
                    drMailBox2["Dates"] = DateTime.Now;
                    drMailBox2["ComputeName"] = System.Net.Dns.GetHostName();
                    drMailBox2["ReceiveUserCode"] = strUserCode;
                    dsMailBox.Tables["T_MailBox2"].Rows.Add(drMailBox2);

                    string strAutoMoveFolder = "否";
                    if (dsData.Tables["Folder"].DefaultView.Count > 0)
                        strAutoMoveFolder = dsData.Tables["Folder"].DefaultView[0]["AutoMoveFolder"].ToString();

                    //得到FolderID
                    if (strBoxType != MailBoxCommon.MailBoxType.Spam.ToString())
                    {
                        if (strAutoMoveFolder == "是")
                        {
                            iFolderID = dsMailBox.Tables["T_MailBox"].Rows[0]["FolderID"] == DBNull.Value ? 0 : (int)dsMailBox.Tables["T_MailBox"].Rows[0]["FolderID"];

                            List<int> _iSubFolderIDList = new List<int>();
                            GetFolderIDWhere(true, dsData.Tables["Folder"], strUserCode, strAccountName, iFolderID);

                            strWhere = "";
                            for (int k = 0; k < _iSubFolderIDList.Count; k++)
                            {
                                if (strWhere == "")
                                    strWhere = _iSubFolderIDList[k].ToString();
                                else
                                    strWhere = strWhere + "," + _iSubFolderIDList[k].ToString();
                            }
                            if (strWhere != "")
                            {
                                strWhere = " FolderID IN (" + strWhere + ")";
                                //
                                mailFolder = new MailBoxCommon.MailFolder();
                                iNewFolderID = mailFolder.GetFolderId(strWhere, dsMailBox, 0);
                                if (iFolderID != iNewFolderID)
                                {
                                    dsMailBox.Tables["T_MailBox"].Rows[0]["FolderID"] = iNewFolderID;
                                }
                            }
                            else
                            {
                                dsMailBox.Tables["T_MailBox"].Rows[0]["FolderID"] = iFolderID;
                            }
                        }
                    }
                    dsMailBox.Tables["T_MailBox"].Rows[0].EndEdit();
                    #endregion

                    //接收的新邮件列表，完整的，克隆到新的数据集；
                    dsNewMailBox = new DataSet();
                    if (dsMailBox.GetChanges() != null)
                    {
                        dsNewMailBox = dsMailBox.GetChanges();
                    }
                    //接收邮件数量增加1
                    iReceiveCount++;
                }
                if (dsNewMailBox == null)
                {
                    jsonResult = "{\"success\":true  ,\"data\":{\"Count\":\"0\",\"Status\":\"成功\"} ,\"message\":\"收取邮件成功！\"}";
                }
                else
                {
                    CustomizableDesignBLL.SaveData(dsNewMailBox.GetChanges(), lstDTNMailBox);
                    jsonResult = "{\"success\":true  ,\"data\":{\"Count\":\"" + iReceiveCount + "\",\"Status\":\"成功\"} ,\"message\":\"收取邮件成功！\"}";
                }
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false  ,\"data\":{},\"message\":\"收取邮件失败！\"}";
                return jsonResult;
            }

            return jsonResult;
        }
        #endregion

        #region 获取邮件列表（收件箱、已发送、垃圾箱、草稿箱）
        public string GetDBMailList(string strUserCode, string strAccountName, string strFolderID, string strBoxType, string strPageIndex, string strPageSize, string strWhere)
        {
            string jsonResult = string.Empty;

            int iPageSize = 30;
            int iPageIndex = 1;
            int iFolderId = -100;

            #region 接口参数处理；[用户名、邮箱帐户、邮件系统归属、邮件系统目录均不为空！]

            //搜索条件地址栏转码
            if (!string.IsNullOrEmpty(strWhere))
            {
                strWhere = Microsoft.JScript.GlobalObject.decodeURIComponent(strWhere);
            }
            //接口参数：用户名、邮箱帐户、系统归属、系统目录不能为空！
            if (string.IsNullOrEmpty(strUserCode))
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"用户名称不能为空！\"}";
            }
            if (string.IsNullOrEmpty(strAccountName))
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"邮箱帐户不能为空！\"}";
            }
            if (string.IsNullOrEmpty(strBoxType))
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"邮件的系统归属不能为空！\"}";
            }
            if (string.IsNullOrEmpty(strFolderID))
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"邮件的系统目录不能为空！\"}";
            }
            else
            {
                iFolderId = Convert.ToInt32(strFolderID);
            }
            //邮件分页的页码
            if (!string.IsNullOrEmpty(strPageIndex))
            {
                iPageIndex = Convert.ToInt32(strPageIndex);
            }
            //邮件分页的单页数目
            if (!string.IsNullOrEmpty(strPageSize))
            {
                iPageSize = Convert.ToInt32(strPageSize);
            }
            #endregion

            //根据接口参数，生成查询条件。注意：搜索及分页条件；
            string strSearch = " where ";
            strSearch = strSearch + " UserCode='" + strUserCode + "' and AccountName='" + strAccountName + "' and  BoxType='" + strBoxType + "' and FolderID=" + iFolderId + " ";
            if (!string.IsNullOrEmpty(strWhere))
            {
                string strfilter = "(Subject like '%'+@filter+'%' or Sender like '%'+@filter+'%' or SenderName like '%'+@filter+'%' or ClientCode like '%'+@filter+'%' or ClientName like '%'+@filter+'%' )";
                strSearch += " and " + strfilter;
            }

            string strViewSort = "ISMarking DESC,InSentTime DESC";
            string strSelectColumn = "MailGUID ,UserCode ,AccountName ,Writer ,ISRead ,ISMarking ,ISRevert ,ISFwd ,ISFwdInSide ,ISReceipt ,BoxType ,ISAttachment ,Sender ,SenderName ,ToList ,CcList ,BccList ,InSentTime ,Subject ,FolderID ,MailSize ,MailPath ,RevertMailGUID ,FwdMailGUID ,OrgIP ,OrgAddress ,ClientType ,ClientCode ,ClientName ,ContactName ,Country ,PurposeModuleName ,PurposePKCode ,PurposeDesc ,ISImportant ,ISTrack";
            string strTableName = "T_MailBox";



            SqlConnection sqlConn = new SqlConnection(strConnectString);
            SqlTransaction sqlTrans = null;
            DataSet dsResult = null;
            //查询邮件列表
            string strSQLMailList = "SELECT * " +
                        "FROM (SELECT ROW_NUMBER() over(order by " + strViewSort + ") as colnum," + strSelectColumn + " FROM " + strTableName + strSearch + ") tab_1 " +
                        "WHERE colnum>(" + iPageIndex.ToString() + "-1)*" + iPageSize.ToString() + " AND colnum<=" + iPageIndex.ToString() + "*" + iPageSize.ToString();
            SqlCommand sqlComMailList;
            SqlDataAdapter sqlAdaMailList;
            //查询邮件数目
            string strSQLMailCount = "SELECT COUNT(*) Row_Count FROM " + strTableName + strSearch;
            SqlCommand sqlComMailCount;
            SqlDataAdapter sqlAdaMailCount;

            try
            {
                sqlConn.Open();
                sqlTrans = sqlConn.BeginTransaction();
                dsResult = new DataSet();
                //邮件列表
                sqlComMailList = new SqlCommand(strSQLMailList, sqlConn);
                if (!string.IsNullOrEmpty(strWhere))
                {
                    sqlComMailList.Parameters.Add("@filter", SqlDbType.VarChar, 200);
                    sqlComMailList.Parameters["@filter"].Value = strWhere;
                }
                sqlComMailList.Transaction = sqlTrans;
                sqlAdaMailList = new SqlDataAdapter(sqlComMailList);
                sqlAdaMailList.Fill(dsResult, "MailList");
                //邮件数目
                sqlComMailCount = new SqlCommand(strSQLMailCount, sqlConn);
                if (!string.IsNullOrEmpty(strWhere))
                {
                    sqlComMailCount.Parameters.Add("@filter", SqlDbType.VarChar, 200);
                    sqlComMailCount.Parameters["@filter"].Value = strWhere;
                }
                sqlComMailCount.Transaction = sqlTrans;
                sqlAdaMailCount = new SqlDataAdapter(sqlComMailCount);
                sqlAdaMailCount.Fill(dsResult, "MailCount");
                //事务提交
                sqlTrans.Commit();
                //返回邮件列表和邮件数目
                jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(dsResult) + "  ,\"message\":\"正常\"}";
                return jsonResult;
            }
            catch (Exception)
            {
                if (sqlTrans != null)
                    sqlTrans.Rollback();
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"获取邮件失败\"}";
                return jsonResult;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                {
                    sqlConn.Close();
                }
            }
            return jsonResult;
        }
        #endregion

        #region 获取邮件内容
        public string GetMailDetail(string strMailGUID)
        {
            string jsonResult = string.Empty;

            DataSet dsMailBox = null;
            List<DataTableName> lstDTNMailBox = new List<DataTableName>();
            DataTableName dtnMailBox = null;
            #region 获取邮件详细信息
            dtnMailBox = new DataTableName();
            dtnMailBox.strSelectSQL = "SELECT * FROM T_MailBox WHERE MailGUID=@MailGUID";
            dtnMailBox.strTableName = "T_MailBox";
            dtnMailBox.SqlSelectParameterList.Add(new SqlParameter("@MailGUID", strMailGUID));
            lstDTNMailBox.Add(dtnMailBox);
            //
            dtnMailBox = new DataTableName();
            dtnMailBox.strSelectSQL = "SELECT * FROM T_MailBox1 WHERE MailGUID=@MailGUID";
            dtnMailBox.strTableName = "T_MailBox1";
            dtnMailBox.SqlSelectParameterList.Clear();
            dtnMailBox.SqlSelectParameterList.Add(new SqlParameter("@MailGUID", strMailGUID));
            lstDTNMailBox.Add(dtnMailBox);
            //
            dtnMailBox = new DataTableName();
            dtnMailBox.strSelectSQL = "Select * FROM T_MailBox2 WHERE MailGUID=@MailGUID";
            dtnMailBox.strTableName = "T_MailBox2";
            dtnMailBox.SqlSelectParameterList.Clear();
            dtnMailBox.SqlSelectParameterList.Add(new SqlParameter("@MailGUID", strMailGUID));
            lstDTNMailBox.Add(dtnMailBox);
            try
            {
                dsMailBox = CustomizableDesignBLL.GetData(lstDTNMailBox, false);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"邮件信息获取失败！\"}";
                return jsonResult;
            }
            if (dsMailBox == null || dsMailBox.Tables.Count <= 0)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"邮件信息获取失败！\"}";
                return jsonResult;
            }
            if (dsMailBox.Tables["T_MailBox"].DefaultView.Count <= 0 || dsMailBox.Tables["T_MailBox2"].DefaultView.Count <= 0)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"邮件信息不存在！\"}";
                return jsonResult;
            }
            #endregion

            #region 参数组，构造邮件对象：收、发、抄、密，主题，正文
            string strBox0MailPath;
            MailService.Mime.MailMessage mail = null;
            string strEMailFile;
            string strSender = string.Empty;   //发件人地址
            string strSenderName = string.Empty;   //发件人姓名
            string strToList = string.Empty;   //收件人
            string strCcList = string.Empty;   //抄送人
            string strSubject = string.Empty;
            string strPurposeModuleName = string.Empty;
            string strPurposePKCode = string.Empty;
            string strPurposeDesc = string.Empty;
            string strMailBody; //邮件体
            bool bIsAttachment = false;
            #endregion

            strSender = dsMailBox.Tables["T_MailBox"].DefaultView[0]["Sender"].ToString();
            strSenderName = dsMailBox.Tables["T_MailBox"].DefaultView[0]["SenderName"].ToString();
            strToList = dsMailBox.Tables["T_MailBox"].DefaultView[0]["ToList"].ToString();
            strCcList = dsMailBox.Tables["T_MailBox"].DefaultView[0]["CcList"].ToString();
            strSubject = dsMailBox.Tables["T_MailBox"].DefaultView[0]["Subject"].ToString();
            strPurposeModuleName = dsMailBox.Tables["T_MailBox"].DefaultView[0]["PurposeModuleName"].ToString();
            strPurposePKCode = dsMailBox.Tables["T_MailBox"].DefaultView[0]["PurposePKCode"].ToString();
            strPurposeDesc = dsMailBox.Tables["T_MailBox"].DefaultView[0]["PurposeDesc"].ToString();
            strMailBody = "";//装载邮件后再读取
            bIsAttachment = dsMailBox.Tables["T_MailBox"].DefaultView[0]["IsAttachment"] == DBNull.Value ? false : (bool)dsMailBox.Tables["T_MailBox"].DefaultView[0]["IsAttachment"];
            strMailGUID = dsMailBox.Tables["T_MailBox"].DefaultView[0]["MailGUID"].ToString();
            List<string> strMailGUIDList = new List<string>();
            strMailGUIDList.Add(strMailGUID);


            //正文中图片CID集合
            List<string> strContentIDList = new List<string>();

            //邮件文件路径：注意与发送接口保持一致。
            strBox0MailPath = dsMailBox.Tables["T_MailBox2"].DefaultView[0]["MailPath"].ToString().ToLower();


            //这个地方，要写邮件上传的路径“D:\智桥系统\ftp\Mail\2016-08-25\Admindxstudying\Sent”
            //但是IIS的虚拟路径尚未指向，所以先暂用配置文件ServerFTP路径。
            string strServerFtp = ConfigurationManager.AppSettings["ServerFtpDir"].ToString();
            string strRelativePath = strBox0MailPath.Replace("/", "\\");
            strEMailFile = strServerFtp+"\\"+ strRelativePath;


            //生成网页IIS请求基干路径
            string strHttpServerAddress = ConfigurationManager.AppSettings["HttpServerAddress"].ToString();
            string strHttpServerPort = ConfigurationManager.AppSettings["HttpServerPort"].ToString();
            
            //网页IIS基干路径
            string strWebTrunkUrl = strHttpServerAddress + ":" + strHttpServerPort;
            string strWebFullUrl = strWebTrunkUrl + "/ftp/AppMail/MailAttach/" + DateTime.Now.ToString("yyyy-MM-dd") + "/Show/";

            //服务器本地基干路径
            string strLocalTrunkDir = Server.MapPath("/ftp/AppMail");
            //服务器附件统一路径
            string strLocalFullDir = strLocalTrunkDir + "\\MailAttach\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\Show\\";
            //格式化
            if (!Directory.Exists(strLocalFullDir))
                Directory.CreateDirectory(strLocalFullDir);
            if (!strLocalFullDir.EndsWith("\\"))
                strLocalFullDir = strLocalFullDir + "\\";

            try
            {
                if (System.IO.File.Exists(strEMailFile))
                {
                    //生成Mail对象；
                    mail = new MailService.Mime.MailMessage();
                    //Mail对象加载本地Mail文件；
                    mail.LoadMessage(strEMailFile);

                    #region 主题与正文的文本内容

                    string strTextBody = "";
                    string strHtmlBody = "";
                    try
                    {
                        strTextBody = mail.BodyPlainText;
                    }
                    catch
                    {
                        strTextBody = "";
                    }
                    try
                    {
                        strHtmlBody = mail.BodyHtmlText;
                    }
                    catch
                    {
                        strHtmlBody = "";
                    }
                    if (String.IsNullOrEmpty(strHtmlBody))
                    {
                        strMailBody = System.Web.HttpUtility.HtmlEncode(strTextBody);
                        if (strTextBody != string.Empty)    //强制转换为HTML
                            strMailBody = "<DIV><FONT face=Arial Narrow size=2>" + strMailBody.Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>") + "</FONT></DIV>";
                    }
                    else
                    {
                        strMailBody = strHtmlBody;
                    }
                    #endregion

                    DataSet dsMailAttachmentList = new DataSet();
                    #region 获取附件数据集
                    DataTable dtMailAttachmentList = MailBoxCommon.GetMailAttachment();
                    dsMailAttachmentList.Tables.Add(dtMailAttachmentList);
                    DataRow drNewMailAttachment;
                    int iSortID = 0;
                    foreach (MailService.Mime.Attachment attachment in mail.Attachments)
                    {
                        drNewMailAttachment = dsMailAttachmentList.Tables[0].NewRow();
                        drNewMailAttachment["MailGUID"] = strMailGUID;
                        drNewMailAttachment["SortID"] = iSortID;
                        iSortID++;
                        drNewMailAttachment["AttachmentName"] = attachment.Filename;
                        if (attachment.Size == 0)
                            continue;
                        drNewMailAttachment["AttachmentSize"] = (int)attachment.Size;
                        drNewMailAttachment["AttachmentFile"] = string.Empty;
                        drNewMailAttachment["IsFile"] = attachment.IsFile;
                        drNewMailAttachment["IsInline"] = attachment.IsInline;
                        drNewMailAttachment["ContentID"] = attachment.ContentID;
                        drNewMailAttachment["AttachmentPath"] = "";
                        //
                        dsMailAttachmentList.Tables[0].Rows.Add(drNewMailAttachment);
                    }
                    dsMailAttachmentList.Tables[0].DefaultView.Sort = "SortID";
                    #endregion

                    int iCidStartIndex = -1;
                    int iCidEndIndex = -1;
                    string strCid;
                    DataRow[] drSelectedRows;
                    string strAttachmentPath;
                    #region 背景的图片处理
                    //背景的时候background=cid:002b01c90cbe$e40e9410$8201a8c0@KFB011,所以要在cid前面以及后面都加上引号,以便跟以前的程序同步
                    if (strMailBody.ToLower().IndexOf("=cid:") >= 0)
                    {
                        foreach (DataRowView drvAtt in dsMailAttachmentList.Tables["T_MailAttachment"].DefaultView)
                        {
                            if (drvAtt["ContentID"].ToString().Trim() == string.Empty)
                            {
                                continue;
                            }
                            strCid = drvAtt["ContentID"].ToString().ToLower();
                            int iBackCidStartIndex = -1;
                            while (true)
                            {
                                iBackCidStartIndex = strMailBody.ToLower().IndexOf("=cid:" + strCid, iBackCidStartIndex + 1);
                                if (iBackCidStartIndex < 0)
                                    break;
                                strMailBody = strMailBody.Replace(strMailBody.Substring(iBackCidStartIndex, strCid.Length + 5), "=\"cid:" + strCid + "\"");
                            }
                        }
                    }
                    while (true)
                    {
                        //src=3D"cid:002b01c90cbe$e40e9410$8201a8c0@KFB011" IMG的SRC显示为这样的时候需要转换为本地
                        iCidStartIndex = strMailBody.ToLower().IndexOf("\"cid:", iCidStartIndex + 1);
                        if (iCidStartIndex < 0)
                            break;
                        iCidEndIndex = strMailBody.IndexOf("\"", iCidStartIndex + 4);
                        if (iCidEndIndex < 0)
                            break;
                        //取得的CID
                        strCid = strMailBody.Substring(iCidStartIndex + 5, iCidEndIndex - iCidStartIndex - 5);
                        //去参照邮件附件表中的内容ID
                        drSelectedRows = dsMailAttachmentList.Tables["T_MailAttachment"].Select("ContentID='" + strCid.Replace("'", "''") + "'");
                        strContentIDList.Add(strCid);
                        if (drSelectedRows.Length == 0)
                            continue;
                        strAttachmentPath = string.Empty;
                        for (int i = 0; i < mail.Attachments.Count; i++)
                        {
                            if (mail.Attachments[i].ContentID.ToLower() != strCid.ToLower())
                            {
                                continue;
                            }
                            string strDBFileName = mail.Attachments[i].Filename;
                            string strSavePath = strLocalFullDir + strDBFileName;

                            string strWebFilePath = strWebFullUrl + strDBFileName;
                            strAttachmentPath = strWebFilePath;

                            //保存邮件正文图片到Web服务器AppMail\MailWebImage\文件夹
                            mail.Attachments[i].Save(strSavePath, true);

                            //保存网络路径到返回数据集
                            drSelectedRows[0]["AttachmentPath"] = strWebFilePath;
                            drSelectedRows[0].EndEdit();
                        }
                        strMailBody = strMailBody.Replace(strMailBody.Substring(iCidStartIndex, iCidEndIndex - iCidStartIndex + 1), "\"" + strAttachmentPath.Replace("\\", "/") + "\"");
                    }
                    if (dsMailBox.Tables.Contains("T_MailBox1"))
                    {
                        if (dsMailBox.Tables["T_MailBox1"].DefaultView.Count > 0)
                        {
                            dsMailBox.Tables["T_MailBox1"].DefaultView[0]["TextBody"] = strMailBody;
                            dsMailBox.Tables["T_MailBox1"].DefaultView[0].EndEdit();
                        }
                    } 
                    #endregion

                    //处理显示内容中包含邮件图片的情况完成
                    #region 显示附件中的图片
                    for (int i = 0; i < mail.Attachments.Count; i++)
                    {
                        //显示图片中的附件，因为CS用的WebBrower，而手机APP只需要知道路径即可。所以（要使用缩略图，暂用原图，稍后处理）
                    }
                    #endregion

                    #region 装载附件，APP这里，不用装载，直接返回，附件的Web路径；
                    for (int i = 0; i < mail.Attachments.Count; i++)
                    {
                        if (mail.Attachments[i].IsInline==true)
                        {
                            continue;
                        }
                        string strDBFileName = mail.Attachments[i].Filename;
                        string strSavePath = strLocalFullDir + strDBFileName;
                        //保存邮件正文图片到Web服务器AppMail\MailWebImage\文件夹
                        mail.Attachments[i].Save(strSavePath, true);

                        string strTempWebPath = strWebFullUrl + strDBFileName;
                        drSelectedRows = dsMailAttachmentList.Tables["T_MailAttachment"].Select("AttachmentName='"+strDBFileName+"'");
                        drSelectedRows[0]["AttachmentPath"] = strTempWebPath;
                        drSelectedRows[0].EndEdit();
                    }
                    #endregion

                    DataTable dtAttach = dsMailAttachmentList.Tables[0].Clone();
                    dtAttach.TableName = "T_AttachFile";
                    foreach (DataRow drRow in dsMailAttachmentList.Tables[0].Rows)
                    {
                        dtAttach.Rows.Add(drRow.ItemArray);
                    }
                    dsMailBox.Tables.Add(dtAttach);
                    jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(dsMailBox) + ",\"message\":\"正常\"}";
                }
                else
                {
                    jsonResult = "{\"success\":false,\"data\":{},\"message\":\"邮件eml不存在！\"}";
                    return jsonResult;
                }
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"邮件信息不存在！\"}";
                return jsonResult;
            }
            return jsonResult;
        }
        #endregion

        #region 发送邮件 原始原理实现代码，仅作参照；
        public string SendMail(string strUserCode, string strMailAddress, string strMailTo, string strMailCopyTo, string strSccretTo, string strSubject, string strType, string strMailBody, string strAttachList)
        {
            /* －－－－－邮件设计
             * 1、把附件上传到服务器，并把文件名称传到APP本地存储；
             * 2、发送邮件，把附件路径、邮箱帐户、邮件接收信息、邮件正文，提交给服务器；
             * 3、服务器端构建一个邮件对象，并保存本地邮件。
             *      1）如果发送成功，就把邮件信息写入到数据库的已发送。
             *      2）如果发送不成功，就把邮件信息写入数据库的草稿箱（垃圾箱）。   
             */
            string jsonResult = string.Empty;
            string _strUserCode = strUserCode;

            string _strMailAddress = Microsoft.JScript.GlobalObject.decodeURIComponent(strMailAddress);
            string _strMailTo = Microsoft.JScript.GlobalObject.decodeURIComponent(strMailTo);
            string _strMailCopyTo = Microsoft.JScript.GlobalObject.decodeURIComponent(strMailCopyTo);
            string _strSccretTo = Microsoft.JScript.GlobalObject.decodeURIComponent(strSccretTo);
            string _strSubject = Microsoft.JScript.GlobalObject.decodeURIComponent(strSubject);
            string _strType = Microsoft.JScript.GlobalObject.decodeURIComponent(strType);
            string _strMailBody = Microsoft.JScript.GlobalObject.decodeURIComponent(strMailBody);
            string _strAttachList = Microsoft.JScript.GlobalObject.decodeURIComponent(strAttachList);

            //登陆帐户的邮箱帐户
            SqlConnection sqlConn = new SqlConnection(strConnectString);
            string strSQLAccound = "SELECT *  FROM T_MailAccount WHERE  UserCode=@UserCode And MailAddress=@MailAddress";
            SqlCommand sqlComAccount;
            SqlDataAdapter sqlAdaAccount;
            DataSet dsAccount;
            #region 登陆帐户
            try
            {
                dsAccount = new DataSet();
                sqlComAccount = new SqlCommand(strSQLAccound, sqlConn);
                sqlComAccount.Parameters.Add("@UserCode", SqlDbType.VarChar, 50);
                sqlComAccount.Parameters["@UserCode"].Value = _strUserCode;
                sqlComAccount.Parameters.Add("@MailAddress", SqlDbType.VarChar, 50);
                sqlComAccount.Parameters["@MailAddress"].Value = _strMailAddress;
                sqlAdaAccount = new SqlDataAdapter(sqlComAccount);
                sqlAdaAccount.Fill(dsAccount, "T_Account");
                sqlConn.Close();
            }
            catch (Exception ex)
            {
                return jsonResult = "{\"success\":false  ,\"data\":{}  ,\"message\":\"" + ex.Message + "\"}";
            }
            if (dsAccount == null)
            {
                return jsonResult = "{\"success\":false  ,\"data\":{}  ,\"message\":\"邮箱地址有误或邮箱地址不存在！\"}";
            }
            #endregion

            string _strSMTPServer = dsAccount.Tables["T_Account"].DefaultView[0]["SMTPServer"].ToString();
            //int _iSMTPPort=dsAccount.Tables["T_Account"].DefaultView[0]["MailPassword"]==DBNull.Value?0 : (int)dsAccount.Tables["T_Account"].DefaultView[0]["MailPassword"];

            //邮件帐户，授权密码；
            string _DESKey = "8^@a)2.Y";
            string strSMTPMailPassword = dsAccount.Tables["T_Account"].DefaultView[0]["MailPassword"].ToString();
            string _strSMTPMailPassword = Custom.UI.EncryptDecryptService.DESDecrypt(_DESKey, strSMTPMailPassword);

            #region 邮件日志保存路径

            string strLogFilePath = Server.MapPath("/ftp/AppMail");
            strLogFilePath = strLogFilePath + "\\MailLog\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            //如果文件夹不存在，创建该文件夹
            if (!Directory.Exists(strLogFilePath))
            {
                Directory.CreateDirectory(strLogFilePath);
            }
            Smtp mailer = new Smtp();
            mailer.Log.Enabled = true;
            mailer.Log.Filename = strLogFilePath + "\\log.txt";
            mailer.Log.Format = LogFormatOptions.AddContextInfo;
            #endregion

            AuthenticationMethods[] authMethodArray = new AuthenticationMethods[] {
                                        AuthenticationMethods.None,
                                        AuthenticationMethods.Auto,
                                        AuthenticationMethods.SaslLogin,
                                        AuthenticationMethods.SaslCramMD5,
                                        AuthenticationMethods.SaslNtlm,
            };
            mailer.DnsServers.Clear();
            mailer.SmtpServers.Clear();
            mailer.SmtpServers.Add(
                    _strSMTPServer,
                    _strMailAddress,
                    _strSMTPMailPassword,
                    authMethodArray[2]
                    );
            // Set message headers.
            mailer.From.AsString = _strMailAddress;
            mailer.To.AsString = _strMailTo;
            mailer.Cc.AsString = _strMailCopyTo;
            mailer.Bcc.AsString = _strSccretTo;
            mailer.Subject = _strSubject;


            // Set message body.
            if (strType.Trim().ToLower() == "html".Trim().ToLower())
            {
                mailer.Message.BodyPlainText = string.Empty;
                mailer.Message.BodyHtmlText = _strMailBody;
            }
            else
            {
                mailer.Message.BodyPlainText = _strMailBody;
                mailer.Message.BodyHtmlText = string.Empty;
            }
            //Clear the log file before sending.
            mailer.Log.Clear();


            //添加附件
            string[] aryAttachItem = _strAttachList.Split(';');
            for (int i = 0; i < aryAttachItem.Length; i++)
            {
                if (string.IsNullOrEmpty(aryAttachItem[i].Trim()))
                    continue;
                if (!System.IO.File.Exists(aryAttachItem[i]))
                    continue;
                mailer.Message.Attachments.Add(aryAttachItem[i].Trim());
            }

            //发送邮件的结果
            string msg = string.Empty;
            try
            {
                bool bo = mailer.Send();
                if (bo)
                {
                    if (mailer.GetRefusedRecipients().Count > 0)
                    {
                        msg = "The message was sent successfully,however those are not " + mailer.GetRefusedRecipients().ToString();
                    }
                    else
                    {
                        msg = "success";
                    }
                }
            }
            catch (Exception ex)
            {
                if (mailer.IsConnected)
                {
                    // This will disconnect on error.
                    try
                    {
                        mailer.Disconnect();
                    }
                    catch (MailServiceException)
                    {
                        msg = "error";
                    }
                }
            }
            if (msg == "success")
            {
                jsonResult = "{\"success\":success  ,\"data\":{}  ,\"message\":\"success\"}";
            }
            else
            {
                jsonResult = "{\"success\":false  ,\"data\":{}  ,\"message\":\"" + msg + "\"}";
            }
            return jsonResult;
        }
        #endregion

        #region 发送邮件－Z版智桥系统，发送邮件
        public string SendDBMail(string strUserCode, string strAccountName, string strMailTo, string strMailCopyTo, string strSccretTo, string strSubject, string strMailBody, string strAttachList, string strMailSign)
        {
            string jsonResult = string.Empty;
            Smtp objSMTP =null;
            SmtpServer objServerSMTP = null;
            System.Net.Mail.SmtpClient objClientSMTP = null;

            #region 参数验证：用户名、邮箱帐户、收件人不能为空
            if (string.IsNullOrEmpty(strUserCode))
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"用户名称不能为空！\"}";
                return jsonResult;
            }
            if (string.IsNullOrEmpty(strAccountName))
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"邮箱帐户不能为空！\"}";
                return jsonResult;
            }
            if (string.IsNullOrEmpty(strMailTo))
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"收件人不能为空！\"}";
                return jsonResult;
            }
            #endregion

            strAccountName = Microsoft.JScript.GlobalObject.decodeURIComponent(strAccountName);
            strSubject = Microsoft.JScript.GlobalObject.decodeURIComponent(strSubject);
            strMailBody = Microsoft.JScript.GlobalObject.decodeURIComponent(strMailBody);
            strAttachList = Microsoft.JScript.GlobalObject.decodeURIComponent(strAttachList);

            //查询用户的邮箱帐号的基本信息
            DataSet dsData = null;
            DataTableName dtnUserAccount = new DataTableName();
            #region 查询邮箱帐号信息
            dtnUserAccount.strSelectSQL = "SELECT *  FROM  T_MailAccount WHERE  UserCode=@UserCode and AccountName=@AccountName ";
            dtnUserAccount.strTableName = "T_MailAccount";
            dtnUserAccount.SqlSelectParameterList.Add(new SqlParameter("@UserCode", strUserCode));
            dtnUserAccount.SqlSelectParameterList.Add(new SqlParameter("@AccountName", strAccountName));
            try
            {
                dsData = CustomizableDesignBLL.GetData(dtnUserAccount, false);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false ,\"data\":{},\"message\":\"查询邮箱邮号信息失败！\"}";
                return jsonResult;
            }
            if (dsData == null || dsData.Tables.Count <= 0 || dsData.Tables[0].DefaultView.Count <= 0)
            {
                jsonResult = "{\"success\":false ,\"data\":{},\"message\":\"系统未查询到邮箱帐号信息！\"}";
                return jsonResult;
            }
            #endregion

            DataSet dsMailBox = null;
            List<DataTableName> lstDTNMailBox = new List<DataTableName>();
            DataTableName dtnMailBox = null;
            #region 查询邮件表结构
            //邮件基本表
            dtnMailBox = new DataTableName();
            dtnMailBox.strSelectSQL = "SELECT * FROM T_MailBox WHERE 1=2";
            dtnMailBox.strTableName = "T_MailBox";
            dtnMailBox.SqlSelectParameterList.Clear();
            lstDTNMailBox.Add(dtnMailBox);
            //邮件主体表
            dtnMailBox = new DataTableName();
            dtnMailBox.strSelectSQL = "SELECT * FROM T_MailBox1 WHERE 1=2";
            dtnMailBox.strTableName = "T_MailBox1";
            dtnMailBox.SqlSelectParameterList.Clear();
            lstDTNMailBox.Add(dtnMailBox);
            //邮件跟踪表
            dtnMailBox = new DataTableName();
            dtnMailBox.strSelectSQL = "SELECT * FROM T_MailBox2 WHERE 1=2";
            dtnMailBox.strTableName = "T_MailBox2";
            dtnMailBox.SqlSelectParameterList.Clear();
            lstDTNMailBox.Add(dtnMailBox);
            try
            {
                dsMailBox = CustomizableDesignBLL.GetData(lstDTNMailBox, false);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false ,\"data\":{},\"message\":\"查询邮件表结构信息失败！\"}";
                return jsonResult;
            }
            #endregion

            //加行
            DataRow drNew = dsMailBox.Tables["T_MailBox"].NewRow();
            DataRow drNew1 = dsMailBox.Tables["T_MailBox1"].NewRow();
            DataRow drNew2 = dsMailBox.Tables["T_MailBox2"].NewRow();
            string strMailGUID = System.Guid.NewGuid().ToString();
            #region 构造新邮件的数据集，用于保存到智桥系统

            drNew["MailGUID"] = strMailGUID;
            drNew["UserCode"] = strUserCode;
            drNew["AccountName"] = strAccountName;
            drNew["Writer"] = strUserCode;
            drNew["ISRead"] = true;
            drNew["ISMarking"] = false;
            drNew["ISImportant"] = false;
            drNew["ISRevert"] = false;
            drNew["ISFwd"] = false;
            drNew["ISFwdInSide"] = false;
            drNew["ISReceipt"] = false;
            drNew["BoxType"] = MailBoxCommon.MailBoxType.Draft.ToString();
            drNew["Charset"] = "utf-8";
            drNew["Priority"] = System.Net.Mail.MailPriority.Normal;
            drNew["ISAttachment"] = false;
            drNew["Sender"] = dsData.Tables["T_MailAccount"].Rows[0]["UserMail"].ToString();
            drNew["SenderName"] = dsData.Tables["T_MailAccount"].Rows[0]["UserName"].ToString();
            drNew["ToList"] = strMailTo;
            drNew["Subject"] = strSubject;
            drNew["FolderID"] = MailBoxCommon._iParentFolderIDDraft;
            drNew["RevertMailGUID"] = "";
            drNew["FwdMailGUID"] = "";
            drNew["ISTrack"] = 0;
            //
            drNew1["MailGUID"] = strMailGUID;
            drNew1["UserCode"] = strUserCode;
            drNew1["AccountName"] = strAccountName;
            //
            drNew2["MailGUID"] = strMailGUID;
            drNew2["UserCode"] = strUserCode;
            drNew2["AccountName"] = strAccountName;
            drNew2["TransferSucc"] = 0;
            //
            dsMailBox.Tables["T_MailBox"].Rows.Add(drNew);
            dsMailBox.Tables["T_MailBox1"].Rows.Add(drNew1);
            dsMailBox.Tables["T_MailBox2"].Rows.Add(drNew2);
            #endregion

            //收件人
            dsMailBox.Tables["T_MailBox"].DefaultView[0]["ToList"] = strMailTo;
            //抄送人
            dsMailBox.Tables["T_MailBox"].DefaultView[0]["CcList"] = strMailCopyTo;
            //密抄
            dsMailBox.Tables["T_MailBox"].DefaultView[0]["BccList"] = strSccretTo;
            //主题
            dsMailBox.Tables["T_MailBox"].DefaultView[0]["Subject"] = strSubject;
            //是否附件
            dsMailBox.Tables["T_MailBox"].DefaultView[0]["ISAttachment"] = strAttachList.Split(';').Length>0;
            //回执
            dsMailBox.Tables["T_MailBox"].DefaultView[0]["ISReceipt"] = false;
            //保存邮件时间
            dsMailBox.Tables["T_MailBox"].DefaultView[0]["InSentTime"] = DateTime.Now;

            #region ……邮件签名、普通模板

            #endregion

            #region ……是否需要审批、邮件归档

            #endregion

            #region ……处理正文中有图片

            #endregion

            MailService.Mime.MailMessage msg = new MailService.Mime.MailMessage();

            #region 生成mailMessage，并保存成本地邮件.eml

            string strToMail;
            string strToName;
            int iStartIndex;
            int iEndIndex;
            if (dsMailBox.Tables["T_MailBox"].DefaultView[0]["Charset"].ToString() != string.Empty)
                msg.Charset = dsMailBox.Tables["T_MailBox"].DefaultView[0]["Charset"].ToString();
            else
                msg.Charset = System.Text.Encoding.Default.BodyName; ;
            msg.From = new MailService.Mime.EmailAddress(dsMailBox.Tables["T_MailBox"].DefaultView[0]["Sender"].ToString(), dsMailBox.Tables["T_MailBox"].DefaultView[0]["SenderName"].ToString());
            msg.Subject = dsMailBox.Tables["T_MailBox"].DefaultView[0]["Subject"].ToString();

            #region 收件人
            string strToList = dsMailBox.Tables["T_MailBox"].DefaultView[0]["ToList"].ToString();
            foreach (string strToString in strToList.Split(new char[] { ',', ';' }))   //收件人以,号或;号分割   
            {
                string strTo = strToString.Trim();
                if (strTo == string.Empty)
                    continue;
                strToMail = strTo;
                strToName = string.Empty;
                iStartIndex = strTo.LastIndexOf('<');
                iEndIndex = strTo.LastIndexOf('>');
                if (iStartIndex >= 0 && iEndIndex >= 0 && iStartIndex < iEndIndex)
                {
                    if (iEndIndex != strTo.TrimEnd(new char[] { ' ' }).Length - 1)
                        continue;   //如果>符不是字串最后一个字符则表示收件人无效
                    strToName = strTo.Substring(0, iStartIndex).Trim();
                    strToMail = strTo.Substring(iStartIndex + 1, iEndIndex - iStartIndex - 1).Trim();
                    if (strToName != string.Empty && strToName.StartsWith("\"") && strToName.EndsWith("\"") && strToName != "\"")
                        strToName = strToName.Substring(1, strToName.Length - 2);
                }
                if (!Custom.UI.Common.CheckString.ISMail(strToMail))
                    continue;   //不是有效的邮件地址取消
                if (strToMail != null && strToMail != string.Empty)
                    msg.To.Add(strToMail, strToName, null);
                //保存收件人地址
                if (!this.IsExistEmail(strToMail, strUserCode))
                {
                    if (strToName == "")
                        strToName = strToMail.Substring(0, strToMail.IndexOf("@"));
                    this.SaveMailContact(strToName, strToMail, strUserCode);
                }
            }
            #endregion

            #region 抄送人
            string strCcList = dsMailBox.Tables["T_MailBox"].DefaultView[0]["CcList"].ToString();
            foreach (string strToString in strCcList.Split(new char[] { ',', ';' }))   //收件人以,号或;号分割   
            {
                string strTo = strToString.Trim();
                if (strTo == string.Empty)
                    continue;
                strToMail = strTo;
                strToName = string.Empty;
                iStartIndex = strTo.LastIndexOf('<');
                iEndIndex = strTo.LastIndexOf('>');
                if (iStartIndex >= 0 && iEndIndex >= 0 && iStartIndex < iEndIndex)
                {
                    if (iEndIndex != strTo.TrimEnd(new char[] { ' ' }).Length - 1)
                        continue;   //如果>符不是字串最后一个字符则表示收件人无效
                    strToName = strTo.Substring(0, iStartIndex).Trim();
                    strToMail = strTo.Substring(iStartIndex + 1, iEndIndex - iStartIndex - 1).Trim();
                    if (strToName != string.Empty && strToName.StartsWith("\"") && strToName.EndsWith("\"") && strToName != "\"")
                        strToName = strToName.Substring(1, strToName.Length - 2);
                }
                if (!Custom.UI.Common.CheckString.ISMail(strToMail))
                    continue;   //不是有效的邮件地址取消
                if (strToMail != null && strToMail != string.Empty)
                    msg.Cc.Add(strToMail, strToName, null);
                //保存收件人地址
                if (!this.IsExistEmail(strToMail, strUserCode))
                {
                    if (strToName == "")
                        strToName = strToMail.Substring(0, strToMail.IndexOf("@"));
                    this.SaveMailContact(strToName, strToMail, strUserCode);
                }
            }
            #endregion

            #region 密送人
            string strBccList = dsMailBox.Tables["T_MailBox"].DefaultView[0]["BccList"].ToString();
            foreach (string strToString in strBccList.Split(new char[] { ',', ';' }))   //收件人以,号或;号分割   
            {
                string strTo = strToString.Trim();
                if (strTo == string.Empty)
                    continue;
                strToMail = strTo;
                strToName = string.Empty;
                iStartIndex = strTo.LastIndexOf('<');
                iEndIndex = strTo.LastIndexOf('>');
                if (iStartIndex >= 0 && iEndIndex >= 0 && iStartIndex < iEndIndex)
                {
                    if (iEndIndex != strTo.TrimEnd(new char[] { ' ' }).Length - 1)
                        continue;   //如果>符不是字串最后一个字符则表示收件人无效
                    strToName = strTo.Substring(0, iStartIndex).Trim();
                    strToMail = strTo.Substring(iStartIndex + 1, iEndIndex - iStartIndex - 1).Trim();
                    if (strToName != string.Empty && strToName.StartsWith("\"") && strToName.EndsWith("\"") && strToName != "\"")
                        strToName = strToName.Substring(1, strToName.Length - 2);
                }
                if (!Custom.UI.Common.CheckString.ISMail(strToMail))
                    continue;   //不是有效的邮件地址取消
                if (strToMail != null && strToMail != string.Empty)
                    msg.Bcc.Add(strToMail, strToName);
                //保存收件人地址
                if (!this.IsExistEmail(strToMail, strUserCode))
                {
                    if (strToName == "")
                        strToName = strToMail.Substring(0, strToMail.IndexOf("@"));
                    this.SaveMailContact(strToName, strToMail, strUserCode);
                }
            }
            #endregion

            #region 邮件添加附件

            try
            {
                string[] aryAttachItem = strAttachList.Split(';');
                for (int i = 0; i < aryAttachItem.Length; i++)
                {
                    if (string.IsNullOrEmpty(aryAttachItem[i].Trim()))
                        continue;
                    if (!System.IO.File.Exists(aryAttachItem[i]))
                        continue;
                    msg.Attachments.Add(aryAttachItem[i].Trim());
                }
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"邮件添加附件失败！\"}";
                return jsonResult;
            }
            #endregion

            #region 保存到本地，使邮件本地化
            string strMailPath = dsMailBox.Tables["T_MailBox"].DefaultView[0]["MailPath"].ToString();
            string strFtpPath = "AppMail/MailBox/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + strUserCode + strAccountName.Replace('\\', '_').Replace('/', '_').Replace('"', '_').Replace('<', '_').Replace('>', '_').Replace('|', '_').Replace('\b', '_').Replace('\0', '_').Replace('\t', '_').Replace('?', '_').Replace('*', '_').Replace(':', '_') + "/Sent/";
            strMailPath = strFtpPath + strMailGUID + ".eml";
            dsMailBox.Tables["T_MailBox"].DefaultView[0]["MailPath"] = strMailPath;

            string strLocalPath = string.Empty;
            //IISWeb保存路径  （Z版系统DB的FTP路径，要切换成IIS的路径保存，必须保持一致）
            string strServerDir = Server.MapPath("/ftp");
            if (!System.IO.Directory.Exists(strServerDir))
                System.IO.Directory.CreateDirectory(strServerDir);
            if (!strServerDir.EndsWith("\\"))
                strServerDir = strServerDir + "\\";

            //服务器IIS根FTP路径，加邮件的FTP路径。
            strLocalPath = strServerDir + strFtpPath;
            if (!System.IO.Directory.Exists(strLocalPath))
                System.IO.Directory.CreateDirectory(strLocalPath);

            strLocalPath = strLocalPath + "\\" + strMailGUID + ".eml";
            int iMailSize = 0;
            try
            {
                iMailSize = msg.Size;
            }
            catch (Exception ex)
            {
                if (ex is System.OutOfMemoryException)
                {
                    jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"邮件附件太大！\"}";
                    return jsonResult;
                }
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"邮件无法保存！\"}";
                return jsonResult;
            }
            dsMailBox.Tables["T_MailBox"].DefaultView[0]["MailSize"] = iMailSize;
            if (iMailSize > 3 * 1024 * 1024)
                GC.Collect();
            if (!msg.SaveMessage(strLocalPath))
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"邮件无法保存到目录中！\"}";
                return jsonResult;
            }
            if (!System.IO.File.Exists(strLocalPath))
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"邮件无法保存到目录中！\"}";
                return jsonResult;
            }
            //感觉休眠一个比较好一点,这个大附件是个问题,NET内存不太好回收
            //System.Threading.Thread.Sleep(500);
            if (iMailSize > 3 * 1024 * 1024)
                GC.Collect();

            #endregion

            #region MD5信息，保存到MailBox2邮件跟踪表。

            string strFileMD5 = Custom.UI.Common.GetMD5HashFromFile(strLocalPath);
            dsMailBox.Tables["T_MailBox2"].DefaultView[0]["LocalPath"] = strLocalPath;
            dsMailBox.Tables["T_MailBox2"].DefaultView[0]["FileMD5"] = strFileMD5;
            dsMailBox.Tables["T_MailBox2"].DefaultView[0]["TransferSucc"] = false;
            dsMailBox.Tables["T_MailBox2"].DefaultView[0]["TransferErrorDesc"] = "刚保存";
            dsMailBox.Tables["T_MailBox2"].DefaultView[0]["Dates"] = DateTime.Now;
            dsMailBox.Tables["T_MailBox2"].DefaultView[0]["ComputeName"] = System.Net.Dns.GetHostName();
            dsMailBox.Tables["T_MailBox2"].DefaultView[0]["ReceiveUserCode"] = strUserCode;
            dsMailBox.Tables["T_MailBox2"].DefaultView[0]["MailPath"] = strMailPath;
            #endregion

            #endregion

            dsMailBox.Tables["T_MailBox"].DefaultView[0].EndEdit();
            dsMailBox.Tables["T_MailBox1"].DefaultView[0].EndEdit();
            dsMailBox.Tables["T_MailBox2"].DefaultView[0].EndEdit();
            List<DataTableName> lstDTNSaveMail = new List<DataTableName>();
            DataTableName dtnSaveMail = null;
            try
            {
                //邮件基本表
                dtnSaveMail = new DataTableName();
                dtnSaveMail.strSelectSQL = " Select * from T_MailBox ";
                dtnSaveMail.strTableName = "T_MailBox";
                lstDTNSaveMail.Add(dtnSaveMail);
                //邮件主体表
                dtnSaveMail = new DataTableName();
                dtnSaveMail.strSelectSQL = " Select * from T_MailBox1 ";
                dtnSaveMail.strTableName = "T_MailBox1";
                lstDTNSaveMail.Add(dtnSaveMail);
                //邮件跟踪表
                dtnSaveMail = new DataTableName();
                dtnSaveMail.strSelectSQL = " Select * from T_MailBox2 ";
                dtnSaveMail.strTableName = "T_MailBox2";
                lstDTNSaveMail.Add(dtnSaveMail);
                //保存邮件信息到数据库
                CustomizableDesignBLL.SaveData(dsMailBox.GetChanges(), lstDTNSaveMail);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"保存邮件信息到数据库失败！\"}";
                return jsonResult;
            }
            #region 邮件发送。邮件保存本地，并回写到智桥数据库后，才正式开始发送邮件；


            objSMTP = new Smtp();
            //邮箱授权码加密密钥
            string _DESKey = "8^@a)2.Y";
            //邮箱程序对象，加载本地邮件
            objSMTP.Message.LoadMessage(strLocalPath);

            #region …？这个地方是否也可以直接把前面的:msg信息直接赋值给邮箱程序。
            //objSMTP.Message = msg;
            #endregion

            string strSender = dsMailBox.Tables["T_MailBox"].DefaultView[0]["Sender"].ToString();
            string strSenderName = dsMailBox.Tables["T_MailBox"].DefaultView[0]["SenderName"].ToString();
            string strCharset = dsMailBox.Tables["T_MailBox"].DefaultView[0]["Charset"].ToString();
            bool bISReceipt = dsMailBox.Tables["T_MailBox"].DefaultView[0]["ISReceipt"] == DBNull.Value ? false : (bool)dsMailBox.Tables["T_MailBox"].DefaultView[0]["ISReceipt"];
            string strAutoCc = string.Empty;

            #region 得到自动抄送的邮件地址
            DataSet dsAutoCC = null;
            #region 查询邮件自动抄送信息
            DataTableName dtnAutoCC = new DataTableName();
            dtnAutoCC.strSelectSQL = "SELECT CCList FROM T_AutoCc WHERE UserCode=@UserCode and AccountName=@AccountName ";
            dtnAutoCC.strTableName = "T_AutoCC";
            dtnAutoCC.SqlSelectParameterList.Clear();
            dtnAutoCC.SqlSelectParameterList.Add(new SqlParameter("@UserCode", strUserCode));
            dtnAutoCC.SqlSelectParameterList.Add(new SqlParameter("@AccountName", strAccountName));
            try
            {
                dsAutoCC = CustomizableDesignBLL.GetData(dtnAutoCC, false);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false ,\"data\":{},\"message\":\"查询邮件表结构信息失败！\"}";
                return jsonResult;
            }
            #endregion
            strAutoCc = string.Empty;

            foreach (DataRowView drv in dsAutoCC.Tables["T_AutoCc"].DefaultView)
            {
                strAutoCc = strAutoCc + ";" + drv["CCList"].ToString();
            }
            if (strAutoCc.Length > 0)
            {
                strAutoCc = strAutoCc.Substring(1);
            }
            #endregion

            DataRow drSenderMailAccount = dsData.Tables["T_MailAccount"].Rows[0];

            #region 得到邮件的发件人的邮箱授权码

            bool    bSMTPType = drSenderMailAccount["SMTPType"] == DBNull.Value ? false : (bool)drSenderMailAccount["SMTPType"];
            string  strSMTPServer = drSenderMailAccount["SMTPServer"].ToString();
            int     iSMTPPort = (int)drSenderMailAccount["SMTPPort"];
            bool    bSMTPSSL = (bool)drSenderMailAccount["SMTPSSL"];
            string  strSMTPVerifyType = drSenderMailAccount["SMTPVerifyType"].ToString();
            string  strSMTPMailAddress = "";
            string  strSMTPMailPassword = "";
            //邮箱的授权码
            if (strSMTPVerifyType == "和收件服务器相同")
            {
                strSMTPMailAddress = drSenderMailAccount["MailAddress"].ToString();
                strSMTPMailPassword = drSenderMailAccount["MailPassword"].ToString();
            }
            else if (strSMTPVerifyType == "自定义")
            {
                strSMTPMailAddress = drSenderMailAccount["SMTPMailAddress"].ToString();
                strSMTPMailPassword = drSenderMailAccount["SMTPMailPassword"].ToString();
            }
            else
            {
                //不需要验证
                strSMTPMailAddress = "";
                strSMTPMailPassword = "";
            }
            //MailPassword是加密过的，需要解密后才能使用
            strSMTPMailPassword = Custom.UI.EncryptDecryptService.DESDecrypt(_DESKey, strSMTPMailPassword);

            #endregion

            #region 初始化SMTP，服务器服务组件信息

            int iPriority = 0;// MailService.Mime.MailPriority.None;
            objServerSMTP = new MailService.SmtpMail.SmtpServer(strSMTPServer, iSMTPPort, iPriority);

            if (bSMTPSSL)
                objServerSMTP.SslMode = MailService.Security.SslStartupMode.OnConnect;
            if (drSenderMailAccount["ISProxy"] == DBNull.Value ? false : (bool)drSenderMailAccount["ISProxy"])
            {
                objServerSMTP.Proxy.Name = drSenderMailAccount["ProxyName"].ToString();
                if (drSenderMailAccount["ProxyProtocol"].ToString() == "SOCKS 4")
                    objServerSMTP.Proxy.Protocol = MailService.Proxy.ProxyProtocol.Socks4;
                if (drSenderMailAccount["ProxyProtocol"].ToString() == "SOCKS 5")
                    objServerSMTP.Proxy.Protocol = MailService.Proxy.ProxyProtocol.Socks5;
                if (drSenderMailAccount["ProxyProtocol"].ToString() == "HTTP")
                    objServerSMTP.Proxy.Protocol = MailService.Proxy.ProxyProtocol.Http;
                objServerSMTP.Proxy.Port = (int)drSenderMailAccount["ProxyPort"];
                if (drSenderMailAccount["ProxyProtocol"].ToString() != "SOCKS 4")
                {
                    objServerSMTP.Proxy.AccountName = drSenderMailAccount["ProxyAccountName"].ToString();
                    objServerSMTP.Proxy.Password = Custom.UI.EncryptDecryptService.DESDecrypt(_DESKey, drSenderMailAccount["ProxyPassword"].ToString());
                }
            }
            #region ……发送邮件模式与频道
            //None	0
            //Regular	1
            //Apop	2
            //SaslUserDefined	4
            //SaslLogin	8
            //SaslPlain	16
            //SaslCramMD5	32
            //SaslDigestMD5	64
            //SaslNtlm	128
            //SaslMsn	256
            //SaslGssApi	512
            //SaslOAuth	1024
            //SaslOAuth2	2048
            //Auto	4095
            #endregion

            int iLoginStyle = 4095;
            if (drSenderMailAccount["LoginStyle"] != DBNull.Value)
                iLoginStyle = (int)drSenderMailAccount["LoginStyle"];
            if (iLoginStyle == 4095)
                objServerSMTP.AuthMethods = MailService.AuthenticationMethods.Auto;
            else
                objServerSMTP.AuthMethods = (MailService.AuthenticationMethods)iLoginStyle;


            objServerSMTP.AccountName = strSMTPMailAddress;
            objServerSMTP.Password = strSMTPMailPassword;
            //把邮件服务器对象
            objSMTP.SmtpServers.Add(objServerSMTP);

            #endregion

            #region 加载SMTP的邮件信息

            objSMTP.From = new MailService.Mime.EmailAddress(strSender, strSenderName);
            objSMTP.ReplyTo.Add(new MailService.Mime.EmailAddress(strSender, strSenderName));
            objSMTP.Charset = strCharset;

            #region 转换To
            objSMTP.To.Clear();
            foreach (string strToString in strToList.Split(new char[] { ',', ';' }))   //收件人以,号或;号分割   
            {
                string strTo = strToString.Trim();
                if (strTo == string.Empty)
                    continue;
                strToMail = strTo;
                strToName = string.Empty;
                iStartIndex = strTo.LastIndexOf('<');
                iEndIndex = strTo.LastIndexOf('>');
                if (iStartIndex >= 0 && iEndIndex >= 0 && iStartIndex < iEndIndex)
                {
                    if (iEndIndex != strTo.TrimEnd(new char[] { ' ' }).Length - 1)
                        continue;   //如果>符不是字串最后一个字符则表示收件人无效
                    strToName = strTo.Substring(0, iStartIndex).Trim();
                    strToMail = strTo.Substring(iStartIndex + 1, iEndIndex - iStartIndex - 1).Trim();
                    if (strToName != string.Empty && strToName.StartsWith("\"") && strToName.EndsWith("\"") && strToName != "\"")
                        strToName = strToName.Substring(1, strToName.Length - 2);
                }
                if (!Custom.UI.Common.CheckString.ISMail(strToMail))
                    continue;   //不是有效的邮件地址取消
                if (strToMail != null && strToMail != string.Empty)
                    objSMTP.To.Add(strToMail, strToName);
            }
            #endregion

            #region 转换Cc
            objSMTP.Cc.Clear();
            foreach (string strCcString in strCcList.Split(new char[] { ',', ';' }))   //收件人以,号或;号分割   
            {
                string strTo = strCcString.Trim();
                if (strTo == string.Empty)
                    continue;
                strToMail = strTo;
                strToName = string.Empty;
                iStartIndex = strTo.LastIndexOf('<');
                iEndIndex = strTo.LastIndexOf('>');
                if (iStartIndex >= 0 && iEndIndex >= 0 && iStartIndex < iEndIndex)
                {
                    if (iEndIndex != strTo.TrimEnd(new char[] { ' ' }).Length - 1)
                        continue;   //如果>符不是字串最后一个字符则表示收件人无效
                    strToName = strTo.Substring(0, iStartIndex).Trim();
                    strToMail = strTo.Substring(iStartIndex + 1, iEndIndex - iStartIndex - 1).Trim();
                    if (strToName != string.Empty && strToName.StartsWith("\"") && strToName.EndsWith("\"") && strToName != "\"")
                        strToName = strToName.Substring(1, strToName.Length - 2);
                }
                if (!Custom.UI.Common.CheckString.ISMail(strToMail))
                    continue;   //不是有效的邮件地址取消
                if (strToMail != null && strToMail != string.Empty)
                    objSMTP.Cc.Add(strToMail, strToName);
            }
            #endregion

            #region 转换Bcc
            objSMTP.Bcc.Clear();
            if (strBccList.Trim() == string.Empty)
                strBccList = strAutoCc;
            else
                strBccList += ";" + strAutoCc;
            foreach (string strBccString in strBccList.Split(new char[] { ',', ';' }))   //收件人以,号或;号分割   
            {
                string strTo = strBccString.Trim();
                if (strTo == string.Empty)
                    continue;
                strToMail = strTo;
                strToName = string.Empty;
                iStartIndex = strTo.LastIndexOf('<');
                iEndIndex = strTo.LastIndexOf('>');
                if (iStartIndex >= 0 && iEndIndex >= 0 && iStartIndex < iEndIndex)
                {
                    if (iEndIndex != strTo.TrimEnd(new char[] { ' ' }).Length - 1)
                        continue;   //如果>符不是字串最后一个字符则表示收件人无效
                    strToName = strTo.Substring(0, iStartIndex).Trim();
                    strToMail = strTo.Substring(iStartIndex + 1, iEndIndex - iStartIndex - 1).Trim();
                    if (strToName != string.Empty && strToName.StartsWith("\"") && strToName.EndsWith("\"") && strToName != "\"")
                        strToName = strToName.Substring(1, strToName.Length - 2);
                }
                if (!Custom.UI.Common.CheckString.ISMail(strToMail))
                    continue;   //不是有效的邮件地址取消
                if (strToMail != null && strToMail != string.Empty)
                    objSMTP.Bcc.Add(strToMail, strToName);
            }
            #endregion


            #endregion

            objSMTP.Subject = strSubject;
            if (bISReceipt)
            {
                objSMTP.Message.ConfirmRead = strSender;
                objSMTP.Message.ConfirmReceipt = strSender;
            }
            int iSendSuccess = 0;
            if (bSMTPType)
            {
                #region 采用非标Send Mail

                objClientSMTP = new System.Net.Mail.SmtpClient(strSMTPServer, iSMTPPort);
                objClientSMTP.UseDefaultCredentials = false;
                if (strSMTPVerifyType == "和收件服务器相同" || strSMTPVerifyType == "自定义")
                {
                    //使用SSL套接字 次序不能错
                    objClientSMTP.EnableSsl = bSMTPSSL;
                    objClientSMTP.UseDefaultCredentials = true;
                    objClientSMTP.Credentials = new System.Net.NetworkCredential(strSMTPMailAddress, strSMTPMailPassword);
                }
                objClientSMTP.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

                #region MailMessage  使用SSL套接字，使用System.Net.Mail.SmtpClient发送。

                System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage();
                mailMsg.Sender = new System.Net.Mail.MailAddress(objSMTP.From.Email, objSMTP.From.DisplayName);
                mailMsg.From = new System.Net.Mail.MailAddress(objSMTP.From.Email, objSMTP.From.DisplayName);
                foreach (MailService.Mime.EmailAddress emailAddress in objSMTP.To)
                    mailMsg.To.Add(new System.Net.Mail.MailAddress(emailAddress.Email, emailAddress.DisplayName));
                foreach (MailService.Mime.EmailAddress emailAddress in objSMTP.Cc)
                    mailMsg.CC.Add(new System.Net.Mail.MailAddress(emailAddress.Email, emailAddress.DisplayName));
                foreach (MailService.Mime.EmailAddress emailAddress in objSMTP.Bcc)
                    mailMsg.Bcc.Add(new System.Net.Mail.MailAddress(emailAddress.Email, emailAddress.DisplayName));
                mailMsg.Subject = objSMTP.Subject;
                mailMsg.IsBodyHtml = true;
                mailMsg.Body = objSMTP.BodyHtmlText;
                mailMsg.BodyEncoding = System.Text.Encoding.GetEncoding(objSMTP.Charset);
                foreach (MailService.Mime.Attachment attachment in objSMTP.Message.Attachments)
                {
                    byte[] byteAttachment = attachment.GetData();
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(byteAttachment);
                    System.Net.Mail.Attachment attachment1 = new System.Net.Mail.Attachment(ms, attachment.Filename);
                    attachment1.ContentId = attachment.ContentID;
                    attachment1.ContentDisposition.Inline = attachment.IsInline;
                    attachment1.Name = attachment.Name;
                    mailMsg.Attachments.Add(attachment1);
                }
                //开始发送邮件
                bool bSendOk = true;
                try
                {
                    objClientSMTP.Send(mailMsg);
                }
                catch
                {
                    bSendOk = false;
                    jsonResult = "{\"success\":false,\"data\":{},\"message\":\"邮件发送失败！\"}";
                }
                if (bSendOk)
                {
                    iSendSuccess = 1;
                    jsonResult = "{\"success\":true  ,\"data\":{\"Process\":\"邮件发送成功！\",\"Mode\":\"非标方式发送。\",\"Status\":\"成功\"}   ,\"message\":\"正常！\"}";
                }
                #endregion

                #endregion
            }
            else
            {
                #region 使用数据库中邮箱帐户发送邮件
                bool bSendOk = true;
                try
                {
                    bSendOk = objSMTP.Send();
                }
                catch (Exception)
                {
                    bSendOk = false;
                    jsonResult = "{\"success\":false,\"data\":{},\"message\":\"邮件发送失败！\"}";
                }
                finally
                { 
                    #region 关闭邮箱服务器的连接
                    if (objSMTP.IsConnected)
                    {
                        try 
                        {
                            objSMTP.Disconnect();
                        }
                        catch
                        {

                        }
                    }
                    #endregion
                }
                if (bSendOk)
                {
                    iSendSuccess = 1;
                    jsonResult = "{\"success\":true  ,\"data\":{\"Process\":\"邮件发送成功！\",\"Mode\":\"智桥平台中登记的邮箱帐户发送。\",\"Status\":\"成功\"}   ,\"message\":\"正常！\"}";
                }
                #endregion
            }
            #endregion

            if (iSendSuccess > 0)
            {
                #region 发送邮件成功，更新当前邮件的草稿箱，修改为已发送状态；
                try
                {
                    string strTempGUID = dsMailBox.Tables["T_MailBox"].DefaultView[0]["MailGuid"].ToString();
                    //1、更新BoxType和FolderID；
                    string strTempBoxType = MailBoxCommon.MailBoxType.Sent.ToString();
                    int iTempFolderID = MailBoxCommon._iParentFolderIDSent;
                    DataTableName dtnUpdate = new DataTableName();
                    dtnUpdate.strExecSQL = " UPDATE T_MailBox SET BoxType=@BoxType,FolderID=@FolderID WHERE MailGUID=@MailGUID ";
                    dtnUpdate.SqlExecParameterList.Add(new SqlParameter("@BoxType", strTempBoxType));
                    dtnUpdate.SqlExecParameterList.Add(new SqlParameter("@FolderID", iTempFolderID));
                    dtnUpdate.SqlExecParameterList.Add(new SqlParameter("@MailGUID", strTempGUID));
                    CustomizableDesignBLL.ExecSQL(dtnUpdate);
                    jsonResult = "{\"success\":true,\"data\":{\"Process\":\"邮件发送成功，保存到已发送成功！\",\"Status\":\"成功\"},\"message\":\"正常！\"}";
                }
                catch (Exception)
                {
                    jsonResult = "{\"success\":true,\"data\":{\"Process\":\"邮件发送成功，保存到已发送失败！\",\"Status\":\"成功\"},\"message\":\"正常！\"}";
                }
                #endregion
            }

            #region 关闭邮箱服务器的连接
            if (objSMTP.IsConnected)
            {
                try
                {
                    objSMTP.Disconnect();
                }
                catch
                {
                }
            }
            #endregion

            return jsonResult;
        }
        #endregion

        #region 保存到地址簿联系人
        public bool SaveMailContact(string strToName, string strToEmail, string strUsercode)
        {
            try
            {
                int iContactID = -1;
                //
                DataSet dsMailContact=null;
                List<DataTableName> DataTableNameList = new List<DataTableName>();
                DataTableName dtn;
                dtn = new DataTableName();
                dtn.strSelectSQL = "SELECT * FROM T_MailContact WHERE ContactID = " + iContactID;
                dtn.strTableName = "T_MailContact";
                dtn.strSaveSQL = "SELECT * FROM T_MailContact";
                DataTableNameList.Add(dtn);
                //
                dtn = new DataTableName();
                dtn.strSelectSQL = "SELECT * FROM T_MailContactEMail WHERE ContactID = " + iContactID;
                dtn.strTableName = "T_MailContactEMail";
                dtn.strSaveSQL = "SELECT * FROM T_MailContactEMail";
                DataTableNameList.Add(dtn);
                try
                {
                    dsMailContact = CustomizableDesignBLL.GetData(DataTableNameList, true);
                }
                catch (Exception)
                {
                    return false;
                }
                if (dsMailContact == null || dsMailContact.Tables.Count == 0)
                    return false;
                //
                DataTableName dtnMax = new DataTableName();
                dtnMax.strSelectSQL = "SELECT Max(ContactID) MaxContactID FROM T_MailContact";
                dtnMax.strTableName = "T_MailContact";
                DataSet dsMax=null;
                try
                {
                    dsMax = CustomizableDesignBLL.GetData(dtnMax, false);
                }
                catch (Exception)
                {
                    return false;
                }
                
                iContactID = 0;
                if (dsMax != null && dsMax.Tables.Count > 0 && dsMax.Tables[0].DefaultView.Count > 0)
                {
                    iContactID = dsMax.Tables[0].DefaultView[0]["MaxContactID"] == DBNull.Value ? 0 : (int)dsMax.Tables[0].DefaultView[0]["MaxContactID"];
                }
                iContactID = iContactID + 1;
                //
                DataRow dr = dsMailContact.Tables["T_MailContact"].NewRow();
                dr["ContactID"] = iContactID;
                dr["UserCode"] = strUsercode;
                dr["FullName"] = strToName;
                dr["DefaultEmail"] = strToEmail;
                dr["Class"] = 3;
                dr["PareContactID"] = -1;
                dr["FolderID"] = -1;
                dsMailContact.Tables["T_MailContact"].Rows.Add(dr);
                //
                DataRow dr1 = dsMailContact.Tables["T_MailContactEMail"].NewRow();
                dr1["ContactID"] = iContactID;
                dr1["SortID"] = 1;
                dr1["EMail"] = strToEmail;
                dr1["ISDefault"] = "是";
                dsMailContact.Tables["T_MailContactEMail"].Rows.Add(dr1);
                //
                if (dsMailContact.GetChanges() != null)
                    CustomizableDesignBLL.SaveData(dsMailContact.GetChanges(), DataTableNameList);
                dsMailContact.AcceptChanges();
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }
        #endregion

        #region 判断邮件地址是否在地址簿中存在
        private bool IsExistEmail(string strEmail, string strUsercode)
        {
            DataSet dsMax = null;
            #region 获取地址簿数据集
            DataTableName dTnMailContact = new DataTableName();
            dTnMailContact.strSelectSQL = "SELECT COUNT(*) Nums FROM T_MailContactEMail WHERE ContactID IN (SELECT ContactID FROM T_MailContact WHERE UserCode='" + strUsercode + "') AND email='" + strEmail + "'";
            dTnMailContact.strTableName = "T_MailContact";
            try
            {
                dsMax = CustomizableDesignBLL.GetData(dTnMailContact, false);
            }
            catch (Exception)
            {
                return false;
            }
            if (dsMax == null)
                return false;
            #endregion

            int iNums = 0;
            #region 获得查询结果的数目；
            if (dsMax != null && dsMax.Tables.Count > 0 && dsMax.Tables[0].DefaultView.Count > 0)
            {
                iNums = dsMax.Tables[0].DefaultView[0]["Nums"] == DBNull.Value ? 0 : (int)dsMax.Tables[0].DefaultView[0]["Nums"];
            }
            #endregion
            return iNums > 0;
        }
        #endregion

        #region 上传附件,支持批量上传，并返回服务器物理路径
        public string UpLoadFile()
        {
            string jsonResult = string.Empty;
            Stream uploadStream = null;  
            FileStream fs = null;

            if (Request.Files.Count == 0)
            {
                string msg="文件不能为空！";
                jsonResult = "{\"success\":false  ,\"data\":{}  ,\"message\":\"" + msg + "\"}";
                return jsonResult;
　　　　    }
            try
            {
                HttpFileCollectionBase ReceiveFiles = Request.Files;
                List<string> lstFilePath = new List<string>();

                for (int i = 0; i < ReceiveFiles.Count; i++)
                {
                    //文件上传，一次上传1M的数据，防止出现大文件无法上传  
                    HttpPostedFileBase postFileBase = Request.Files[i];
                    uploadStream = postFileBase.InputStream;
                    int bufferLen = 1024;
                    byte[] buffer = new byte[bufferLen];
                    int contentLen = 0;

                    //获取原始文件名称与后缀名称
                    string strFileName = Path.GetFileName(postFileBase.FileName);
                    string strExtFileName = Path.GetExtension(postFileBase.FileName);

                    //附件短名称，修改成GUID文件名称（如有需要再修改回来）
                    strFileName = System.Guid.NewGuid().ToString() + strExtFileName;
                    
                    #region 保存路径

                    string strIISFtpDir = Server.MapPath("/ftp");
                    if (!System.IO.Directory.Exists(strIISFtpDir))
                        System.IO.Directory.CreateDirectory(strIISFtpDir);
                    if (!strIISFtpDir.EndsWith("\\"))
                        strIISFtpDir = strIISFtpDir + "\\";

                    //相对路径
                    string strRelativeDir = "AppMail\\MailAttach\\" + DateTime.Now.ToString("yyyy-MM-dd")+"\\Sent\\";
                    //绝对目录
                    string strLocalPath = strIISFtpDir + strRelativeDir;
                    if (!Directory.Exists(strLocalPath))
                        Directory.CreateDirectory(strLocalPath);
                    if(!strLocalPath.EndsWith("\\"))
                        strLocalPath = strLocalPath + "\\";

                    //保存路径-服务器上的物理路径
                    string strFilePath = strLocalPath+ strFileName.Trim();
                    #endregion

                    //写入文件
                    fs = new FileStream(strFilePath, FileMode.Create, FileAccess.ReadWrite);
                    while ((contentLen = uploadStream.Read(buffer, 0, bufferLen)) != 0)
                    {
                        fs.Write(buffer, 0, bufferLen);
                        fs.Flush();
                    }
                    //文件流要注意关闭；（批量附件，每写入完成一个文件，文件流要注意关闭一下；）
                    fs.Close();

                    //把附件保存信息，要反馈给APP。
                    lstFilePath.Add(strFilePath);
                }
                jsonResult = "{\"success\":true ,\"data\":{ \"fileList\" :" + JsonConvert.SerializeObject(lstFilePath) + " } ,\"message\":\"正常\"}";
            }
            catch (Exception ex)
            {
                return jsonResult = "{\"success\":false  ,\"data\":{}  ,\"message\":\"" + ex.Message + "\"}";
            }
            finally 
            {
                if (null != fs)
                {
                    fs.Close();
                }
                if (null != uploadStream)
                {
                    uploadStream.Close();
                }  
            }
            return jsonResult;
        }
        #endregion 

        #region 获取，用户的联系人列表
        public string GetContact(string strUserCode)
        {
            string jsonResult = string.Empty;
            DataSet dsResult = null;
            DataTableName dTnMailContact = new DataTableName();
            dTnMailContact.strSelectSQL = "SELECT * FROM T_MailContact WHERE  UserCode = @UserCode and (Class=1 or Class=3) ";
            dTnMailContact.SqlSelectParameterList.Clear();
            dTnMailContact.SqlSelectParameterList.Add(new System.Data.SqlClient.SqlParameter("@UserCode",strUserCode));
            dTnMailContact.strTableName = "T_MailContact";
            try
            {
                dsResult = CustomizableDesignBLL.GetData(dTnMailContact, false);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"获取联系人失败！\"}";
                return jsonResult;
            }
            if (dsResult != null)
            {
                jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(dsResult) + "  ,\"message\":\"正常\"}";
                return jsonResult;
            }
            else
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"获取联系人失败！\"}";
                return jsonResult;
            }
        }
        #endregion

        #region 获取，用户的邮箱帐户列表
        public string GetAccount(string strUserCode)
        {
            string jsonResult = string.Empty;
            DataSet dsResult = null;
            DataTableName dTnMailAccount = new DataTableName();
            dTnMailAccount.strSelectSQL = "SELECT AccountName ,UserCode ,UserName ,UserMail,MailAddress  FROM T_MailAccount WHERE  UserCode=@UserCode";
            dTnMailAccount.SqlSelectParameterList.Clear();
            dTnMailAccount.SqlSelectParameterList.Add(new System.Data.SqlClient.SqlParameter("@UserCode", strUserCode));
            dTnMailAccount.strTableName = "T_MailAccount";
            try
            {
                dsResult = CustomizableDesignBLL.GetData(dTnMailAccount, false);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false  ,\"data\":{},\"message\":\"系统查询失败！\"}";
                return jsonResult;
            }
            if (dsResult == null)
            {
                jsonResult = "{\"success\":false  ,\"data\":{},\"message\":\"获取邮箱帐号失败！\"}";
                return jsonResult;
            }
            else
            {
                jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(dsResult) + "  ,\"message\":\"正常\"}";
                return jsonResult;
            }
        }
        #endregion

        #region 反射：利用反射，求出控制器中，接口方法的完整网络地址（包含地址栏参数）
        public string Method()
        {
            MailBoxController au = new MailBoxController();
            Type t = typeof(MailBoxController);
            string strControler = "MailBoxController";
            strControler = strControler.Replace("Controller", "").Trim();

            string jsonResult = "";
            List<string> lstResult = new List<string>();
            List<string> lstMethod = new List<string>();
            System.Collections.Hashtable hsParams = new System.Collections.Hashtable();


            System.Reflection.MethodInfo[] methods = t.GetMethods();
            for (int i = 0; i < methods.Length; i++)
            {
                System.Reflection.MethodInfo me = methods[i];
                string meName = me.Name;
                lstMethod.Add(meName);

                System.Reflection.ParameterInfo[] pars = me.GetParameters();
                for (int j = 0; j < pars.Length; j++)
                {
                    System.Reflection.ParameterInfo pa = pars[j];
                    string paName = pa.Name;
                    hsParams.Add(meName + j, paName);
                }
            }
            string strAddress1 = "localhost:5350/" + strControler + "/";
            for (int i = 0; i < lstMethod.Count; i++)
            {
                string strParas = "";
                string strMeName = lstMethod[i];
                foreach (System.Collections.DictionaryEntry item in hsParams)
                {
                    //KEY名称的长度仅比对应的方法的名称的长度多一位；（进行一次过滤；）
                    int iMeLength = strMeName.Length;
                    int iKeyLength = item.Key.ToString().Length;
                    bool bIsSure = iKeyLength - iMeLength == 1;

                    if (item.Key.ToString().Trim().Contains(strMeName.Trim()) && bIsSure)
                    {
                        strParas += item.Value.ToString() + "=&";
                    }
                }
                string strAddress = strAddress1 + strMeName + "?" + strParas;
                if (strAddress.EndsWith("&"))
                {
                    strAddress = strAddress.Substring(0, strAddress.Length - 1);
                }
                //正常情况下，我们创建的方法，会排序在类，在FrameWork中默认生成的方法的前面。（所以取最后一个自定义的方法名可以再次过滤；）
                if (strAddress.Contains("Method"))
                    break;
                lstResult.Add(strAddress);
            }
            jsonResult = JsonConvert.SerializeObject(lstResult);
            return jsonResult;
        }
        #endregion
    }
}
